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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
use std::fs::File;
use std::io::ErrorKind;
fn main() {
// panic!("crash and burn");
// let f = File::open("hello.txt");
// let f = match f {
// Ok(file) => file,
// Err(error) => match error.kind() {
// ErrorKind::NotFound => match File::create("hello.txt") {
// Ok(fc) => fc,
// Err(e) => panic!("Problem creating the file: {:?}", e),
// },
// other_error => {
// panic!("Problem opening file: {:?}", other_error)
// }
// },
// };
// Rustacean style
// let f = File::open("hello.txt").unwrap_or_else(|error| {
// if error.kind() == ErrorKind::NotFound {
// File::create("hello.txt").unwrap_or_else(|error| {
// panic!("Problem creating the file: {:?}", error);
// })
// } else {
// panic!("Problem opening file: {:?}", error);
// }
// });
// Shortcut
// let f = File::open("hello.txt").unwrap();
// let f = File::open("hello.txt").expect("Failed to open hello.txt");
// Propagating
use std::io;
use std::io::Read;
// fn read_username_from_file() -> Result<String, io::Error> {
// let f = File::open("hello.txt");
// let mut f = match f {
// Ok(file) => file,
// Err(e) => return Err(e),
// };
// let mut s = String::new();
// match f.read_to_string(&mut s) {
// Ok(_) => Ok(s),
// Err(e) => Err(e),
// }
// }
// Propagating shortcut
// fn read_username_from_file() -> Result<String, io::Error> {
// let mut f = File::open("hello.txt")?;
// let mut s = String::new();
// f.read_to_string(&mut s)?;
// Ok(s)
// }
// Chaining
// fn read_username_from_file() -> Result<String, io::Error> {
// let mut s = String::new();
// File::open("hello.txt")?.read_to_string(&mut s)?;
// Ok(s)
// }
// Using `fs::read_to_string`
use std::fs;
fn read_username_from_file() -> Result<String, io::Error> {
fs::read_to_string("hello.txt")
}
let r = read_username_from_file();
println!("{:?}", r);
}
|