Result enumResult<T, E>panic!panic!panic!("message")
RUST_BACKTRACE = 1 to print a backtracepanic = 'abort' in Cargo.toml to quit without cleaning the stackResultT is the type of the returned value on successE is the type of the error on failureT = std::fs::FileE = std::io::Erroruse std::fs::File;
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:?}"),
};
}Ok) -> std::fs::FileErr) -> close the programuse 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:?}"),
},
other_error => {
panic!("Problem opening the file: {other_error:?}");
}
},
};
}Ok) -> std::fs::FileErr) ->
ErrorKind::NotFound) -> create file
Ok) -> std::fs::Filepanic! on error shortcutsunwrap
Ok -> valueErr -> panic!use std::fs::File;
use std::io::{self, Read};
fn read_username_from_file() -> Result<String, io::Error> {
let username_file_result = File::open("hello.txt");
let mut username_file = match username_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),
}
}? returns value or returns error (early)
?? is used on
Result, and inner function returns ResultResult or panic!?Result
panic!