Skip to content

Commit

Permalink
feat: error propagation shortcut
Browse files Browse the repository at this point in the history
Signed-off-by: Fredrik Klingenberg <[email protected]>
  • Loading branch information
fredrkl committed Mar 31, 2024
1 parent ff776ca commit 77fea8d
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion projects/panic/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
use std::fs::File;
use std::io::{self, ErrorKind};
use std::io::Read;

fn main() {
let greeting_file_result = File::open("hello.txt");
let _greeting_file = match greeting_file_result {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {:?}", error),
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 the file: {:?}", other_error)
}
},
};
}

fn read_username_from_file() -> 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)
}

0 comments on commit 77fea8d

Please sign in to comment.