aolifu_rust/
panic.rs

1use std::fs::File;
2use std::io;
3use std::io::{ErrorKind, Read};
4
5pub fn open_file() {
6    let f = File::open("hello.txt");
7
8    let f = match f {
9        Ok(file) => file,
10        Err(error) => {
11            panic!("Error opening file {:?}", error);
12        }
13    };
14}
15
16pub fn open_file_two() {
17    let f = File::open("hello.txt");
18    let f = match f {
19        Ok(file) => file,
20        Err(error) => match error.kind() {
21            ErrorKind::NotFound => match File::create("hello.txt") {
22                Ok(file) => file,
23                Err(error) => panic!("Error create file: {:?}", error)
24            },
25            other_error => panic!("Error open the file: {:?}", other_error)
26
27        }
28    };
29}
30
31pub fn open_file_three() {
32    let f = File::open("hello.txt").unwrap_or_else(
33        |error| {
34            if error.kind() == ErrorKind::NotFound {
35                File::create("hello.txt").unwrap_or_else(
36                    |error| {
37                        panic!("error create file {:?}", error);
38                    }
39                )
40            } else {
41                panic!("error opening the file {:?}", error);
42            }
43        }
44    );
45}
46
47pub fn spread_error() -> Result<String, io::Error> {
48    let f = File::open("hello.txt");
49    let mut f = match f {
50        Ok(file) => file,
51        Err(e) => return Err(e),
52    };
53
54    let mut s = String::new();
55    // the last expression is result
56    match f.read_to_string(&mut s) {
57        Ok(_) => Ok(s),
58        Err(e) => Err(e),
59    }
60}
61
62pub fn spread_error_two() -> Result<String, io::Error> {
63    let mut f = File::open("hello.txt")?;
64    let mut s = String::new();
65    f.read_to_string(&mut s)?;
66    Ok(s)
67}
68
69pub fn spread_error_three() -> Result<String, io::Error> {
70    let mut s = String::new();
71    File::open("hello.txt")?.read_to_string(&mut s)?;
72    Ok(s)
73}