This program implements simple result-handling and uses the question mark to propagate an error from another function. In main we call the test() function twice.
fn test_inner(argument: usize) -> Result<usize, &'static str> {
if argument == 6 {
Err(
"Not valid")
} else {
Ok(argument)
}
}
fn test(argument: usize) -> Result<usize, &'static str> {
// Use question mark to propagate the error from another call.
test_inner(argument)?;
// Valid.
Ok(100)
}
fn main() {
// Call with argument 5, this is valid.
if let Ok(result) = test(5) {
println!(
"Result: {result}");
}
// Call with argument 6, this causes an error.
let result = test(6).unwrap();
println!(
"Result: {result}");
}
Result: 100
thread main panicked at called Result::unwrap() on an Err value:
"Not valid", ...
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace