diff --git a/ch09/error_propagation b/ch09/error_propagation new file mode 100755 index 0000000..bff2210 Binary files /dev/null and b/ch09/error_propagation differ diff --git a/ch09/error_propagation.rs b/ch09/error_propagation.rs new file mode 100644 index 0000000..4d0d613 --- /dev/null +++ b/ch09/error_propagation.rs @@ -0,0 +1,33 @@ +use std::fs::File; +use std::io::{self, Read}; + +fn read_username_short() -> Result { + 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 { + 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); +} diff --git a/ch09/fopen b/ch09/fopen new file mode 100755 index 0000000..1202d47 Binary files /dev/null and b/ch09/fopen differ diff --git a/ch09/fopen.rs b/ch09/fopen.rs new file mode 100644 index 0000000..8796118 --- /dev/null +++ b/ch09/fopen.rs @@ -0,0 +1,18 @@ +use std::fs::File; +use std::io::ErrorKind; + +fn main() { + let greeting_file_result = File::open("hello.txt"); + let greeting_file = match greeting_file_result { + 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:?}"), + }, + _ => { + panic!("Problem opening the file: {error:?}"); + } + }, + }; +} diff --git a/ch09/hello.txt b/ch09/hello.txt new file mode 100644 index 0000000..e69de29 diff --git a/ch09/outofbounds b/ch09/outofbounds new file mode 100755 index 0000000..fbc7681 Binary files /dev/null and b/ch09/outofbounds differ diff --git a/ch09/outofbounds.rs b/ch09/outofbounds.rs new file mode 100644 index 0000000..62179df --- /dev/null +++ b/ch09/outofbounds.rs @@ -0,0 +1,5 @@ +fn main() { + let a = vec![1, 2, 3]; + + a[99]; +} diff --git a/ch09/panic b/ch09/panic new file mode 100755 index 0000000..fd7e065 Binary files /dev/null and b/ch09/panic differ diff --git a/ch09/panic.rs b/ch09/panic.rs new file mode 100644 index 0000000..f1a8666 --- /dev/null +++ b/ch09/panic.rs @@ -0,0 +1,3 @@ +fn main() { + panic!("Panic in the disco!"); +} diff --git a/ch09/username.txt b/ch09/username.txt new file mode 100644 index 0000000..70e8367 --- /dev/null +++ b/ch09/username.txt @@ -0,0 +1 @@ +jras