use std::fs;
use std::fs::File;
use std::io::{ErrorKind, Read};
pub fn result_def() {
let f = File::open("hello.txt");
match f {
Ok(file) => file,
Err(error) =>
match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Error"),
}
_ => panic!("Error"),
}
};
}
pub fn result_unwrap() {
let f = File::open("hello.txt").unwrap();
}
pub fn result_expect() {
let f = File::open("hello.txt").expect("Failed to open hello.txt");
}
pub fn result_propagating_panic() {
let username = read_username_from_file();
let username = match username {
Ok(username) => username,
Err(error) => panic!("Failed to read username: {}", error),
};
println!("{}", username);
}
pub fn read_username_from_file() -> Result<String, std::io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => match e.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => return Err(e),
},
_ => return Err(e),
},
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
pub fn read_username_from_file_question_mark() -> Result<String, std::io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
pub fn read_username_from_file_std_lib() -> Result<String, std::io::Error> {
fs::read_to_string("hello.txt")
}