ch09
This commit is contained in:
parent
10b29ad9cb
commit
e1246d346d
10 changed files with 60 additions and 0 deletions
BIN
ch09/error_propagation
Executable file
BIN
ch09/error_propagation
Executable file
Binary file not shown.
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);
|
||||
}
|
||||
BIN
ch09/fopen
Executable file
BIN
ch09/fopen
Executable file
Binary file not shown.
18
ch09/fopen.rs
Normal file
18
ch09/fopen.rs
Normal file
|
|
@ -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:?}");
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
0
ch09/hello.txt
Normal file
0
ch09/hello.txt
Normal file
BIN
ch09/outofbounds
Executable file
BIN
ch09/outofbounds
Executable file
Binary file not shown.
5
ch09/outofbounds.rs
Normal file
5
ch09/outofbounds.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
fn main() {
|
||||
let a = vec![1, 2, 3];
|
||||
|
||||
a[99];
|
||||
}
|
||||
BIN
ch09/panic
Executable file
BIN
ch09/panic
Executable file
Binary file not shown.
3
ch09/panic.rs
Normal file
3
ch09/panic.rs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
panic!("Panic in the disco!");
|
||||
}
|
||||
1
ch09/username.txt
Normal file
1
ch09/username.txt
Normal file
|
|
@ -0,0 +1 @@
|
|||
jras
|
||||
Loading…
Add table
Add a link
Reference in a new issue