ch09
This commit is contained in:
parent
10b29ad9cb
commit
e1246d346d
10 changed files with 60 additions and 0 deletions
33
ch09/error_propagation.rs
Normal file
33
ch09/error_propagation.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
|
||||
fn read_username_short() -> Result<String, io::Error> {
|
||||
let mut username_file = File::open("username.txt")?;
|
||||
let mut username = String::new();
|
||||
username_file.read_to_string(&mut username)?;
|
||||
Ok(username)
|
||||
}
|
||||
|
||||
fn read_username_long() -> Result<String, io::Error> {
|
||||
let file_result = File::open("username.txt");
|
||||
|
||||
let mut username_file = match 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),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let username_long = read_username_long().expect("Failed to read username");
|
||||
let username_short = read_username_short().expect("Failed to read username");
|
||||
|
||||
println!("{}", username_long);
|
||||
println!("{}", username_short);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue