Macro code_spells::reparo

source ·
macro_rules! reparo {
    ($result:expr, move |$arg_name:pat_param| $body:expr) => { ... };
    ($result:expr, |$arg_name:pat_param| $body:expr) => { ... };
    ($result:expr, $alt:expr) => { ... };
}
Expand description

Alias for Result::unwrap_or and Result::unwrap_or_else. Automatically chooses unwrap_or_else if given a closure, and unwrap_or if given an expression that is not a closure.

Example

fn foo(x: u8) -> Result<u8, u8> {
    if x < 125 {
        Ok(x)
    } else {
        Err(x)
    }
}
let five = 5;
assert_eq!(reparo!(foo(5), five), 5); // unwrap_or
assert_eq!(reparo!(foo(255), u8::MAX), u8::MAX); // unwrap_or
assert_eq!(reparo!(foo(255), |_| 5), 5); // unwrap_or_else
let primes = vec![2, 3, 5];
assert_eq!(reparo!(foo(255), move |_| primes.into_iter().sum()), 10); // unwrap_or_else

Note

If the second argument is the name of a function this macro will not work.

fn ten() -> u8 { 10 }
assert_eq!(reparo!(foo(255), ten), 10);

We can make it work by converting the function to a closure

assert_eq!(reparo!(foo(255), |_| ten()), 10); // uses unwrap_or_else

or by calling the function in the macro.

assert_eq!(reparo!(foo(255), ten()), 10); // uses unwrap_or