Is there something similar to the ?
shortcut which instead of returning a result from a function when there is an error, returns a predefined value?
Basical
There is no such utility, but you can always write a macro:
macro_rules! return_if_err {
( $to_test:expr, $default:expr ) => (
if $to_test.is_err() {
return $default;
}
)
}
fn pop_or_default(mut v: Vec) -> i32 {
let result = v.pop();
return_if_err!(result.ok_or(()), 123);
result.unwrap()
}
fn main() {
assert_eq!(pop_or_default(vec![]), 123);
}
You cannot return from an outer scope from a closure.