66 lines
1.9 KiB
Rust
66 lines
1.9 KiB
Rust
use std::fs;
|
|
use std::fs::File;
|
|
use std::io::{Error, ErrorKind, Read};
|
|
|
|
fn main() {
|
|
let _str = handle_errors_with_match();
|
|
|
|
let _str = match handle_errors_with_closures() {
|
|
Ok(_) => println!("Opened or created the file successfully!"),
|
|
Err(e) => panic!("There was a problem opening the file: {:?}", e),
|
|
};
|
|
|
|
let _str = match read_username_from_file() {
|
|
Ok(_) => println!("Opened or created the file successfully!"),
|
|
Err(e) => panic!("There was a problem opening the file: {:?}", e),
|
|
};
|
|
|
|
let _str = match easy_mode() {
|
|
Ok(_) => println!("Opened or created the file successfully!"),
|
|
Err(e) => panic!("There was a problem opening the file: {:?}", e),
|
|
};
|
|
}
|
|
|
|
fn easy_mode() -> Result<String, Error> {
|
|
fs::read_to_string("hello.txt")
|
|
}
|
|
|
|
fn read_username_from_file() -> Result<String, Error> {
|
|
let mut s = String::new();
|
|
|
|
File::open("hello.txt")?.read_to_string(&mut s)?;
|
|
|
|
Ok(s)
|
|
}
|
|
|
|
fn handle_errors_with_closures () -> Result<File, File> {
|
|
File::open("hello.txt").map_err(|error| {
|
|
if error.kind() == ErrorKind::NotFound {
|
|
File::create("hello.txt").unwrap_or_else(|error| {
|
|
panic!("Tried to create file but there was a problem: {:?}", error);
|
|
})
|
|
} else {
|
|
panic!("There was a problem opening the file: {:?}", error);
|
|
}
|
|
})
|
|
}
|
|
|
|
fn handle_errors_with_match () -> File {
|
|
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!("Tried to create file but there was a problem: {:?}", e),
|
|
},
|
|
other_error => panic!("There was a problem opening the file: {:?}", other_error),
|
|
},
|
|
};
|
|
|
|
println!("Opened or created the file successfully!");
|
|
|
|
f
|
|
}
|