Returning default value from function when result is error

后端 未结 3 2003
不思量自难忘°
不思量自难忘° 2021-01-23 02:51

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

3条回答
  •  后悔当初
    2021-01-23 03:03

    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.

提交回复
热议问题