Result
enumResult<T, E>
panic!
panic!
panic!("message")
RUST_BACKTRACE = 1
to print a backtracepanic = 'abort'
in Cargo.toml
to quit without cleaning the stackResult
T
is the type of the returned value on successE
is the type of the error on failureT
= std::fs::File
E
= std::io::Error
use 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::File
Err
) -> 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::File
Err
) ->
ErrorKind::NotFound
) -> create file
Ok
) -> std::fs::File
panic!
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 Result
Result
or panic!
?Result
panic!