rust_learning/panic/
result.rs1use std::fs;
2use std::fs::File;
3use std::io::{ErrorKind, Read};
4
5pub fn result_def() {
7 let f = File::open("hello.txt");
8 match f {
9 Ok(file) => file,
10 Err(error) =>
11 match error.kind() {
12 ErrorKind::NotFound => match File::create("hello.txt") {
13 Ok(fc) => fc,
14 Err(e) => panic!("Error"),
15 }
16 _ => panic!("Error"),
17 }
18 };
19}
20
21pub fn result_unwrap() {
26 let f = File::open("hello.txt").unwrap();
28}
29
30pub fn result_expect() {
32 let f = File::open("hello.txt").expect("Failed to open hello.txt");
36}
37
38pub fn result_propagating_panic() {
40 let username = read_username_from_file();
41 let username = match username {
42 Ok(username) => username,
43 Err(error) => panic!("Failed to read username: {}", error),
44 };
45 println!("{}", username);
46}
47
48pub fn read_username_from_file() -> Result<String, std::io::Error> {
50 let f = File::open("hello.txt");
51 let mut f = match f {
52 Ok(file) => file,
53 Err(e) => match e.kind() {
54 ErrorKind::NotFound => match File::create("hello.txt") {
55 Ok(fc) => fc,
56 Err(e) => return Err(e),
57 },
58 _ => return Err(e),
59 },
60 };
61 let mut s = String::new();
62 match f.read_to_string(&mut s) {
63 Ok(_) => Ok(s),
64 Err(e) => Err(e),
65 }
66}
67
68pub fn read_username_from_file_question_mark() -> Result<String, std::io::Error> {
73 let mut s = String::new();
81 File::open("hello.txt")?.read_to_string(&mut s)?;
82 Ok(s)
83}
84
85pub fn read_username_from_file_std_lib() -> Result<String, std::io::Error> {
87 fs::read_to_string("hello.txt")
88}
89