summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-9-error-handling/result/src/main.rs
blob: 265250cec82645ce580d6c2ebe327a8afd18b4cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::fs::{Self,File};
use std::io::{Self, Read, ErrorKind};

fn main() {
    let greeting_file_result = File::open("hello.txt");

    let greeting_file = match greeting_file_result {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create("hello.txt") {
                Ok(fc) => fc,
                Err(e) => panic!("problem opening file {:?}",e),
            },
            other_error => {
                panic!("problem opening file {:?}",other_error);
            }
        },
    };

    // or use unwrap, it will return value or panic just like match
    // let greeting_file = File::open("hello.txt").unwrap();
}

// functions to read username from file
// each one is a shorter solution of its previous one.
fn read_username_from_file() -> Result<String, io::Error> {
    let username_file_result = File::open("hello.txt");

    let username_file = match username_file_result {
        Ok(file) => file,
        Err(e) =>   return Err(e),
    };

    let mut username = String::new();

    match username_file.read_to_string(&mut username) {
        Ok(_) => Ok(username),
        Err(e) => Err(e),
    }
}

// ? is like match, but shorter
// return content of Ok() if true, or return Err() from whole function
fn read_username_from_file_short() -> Result<String, io::Error> {
    let mut username_file = File::open("hello.txt")?;

    let mut username = String::new();

    username_file.read_to_string(&mut username)?;
    Ok(username)
}

fn read_username_from_file_even_short() -> Result<String, io::Error> {
    let mut username = String::new();

    File::open("hello.txt")?.read_to_string(&mut username)?;
    Ok(username)
}

fn read_username_from_file_shortest() -> Result<String, io::Error> {
    fs::read_to_string("hello.txt")
}