Macro konst::result::unwrap_or_else

source ·
macro_rules! unwrap_or_else {
    ($res:expr, |$param:pat_param| $expr:expr $(,)?) => { ... };
    ($opt:expr, | $($anything:tt)* ) => { ... };
    ($res:expr, $function:expr $(,)?) => { ... };
}
Expand description

A const equivalent of Result::unwrap_or_else

§Example

use konst::result;

// Necessary for type inference reasons.
type Res = Result<u32, u32>;

const ARR: &[u32] = &[
    // You can use a closure-like syntax to run code when the Result argument is Err.
    // `return` inside the "closure" returns from the function where this macro is called.
    result::unwrap_or_else!(Res::Ok(3), |_| loop{}),
    result::unwrap_or_else!(Res::Err(8), |x| x + 5),

    // You can also pass functions
    result::unwrap_or_else!(Res::Ok(21), add_34),
    result::unwrap_or_else!(Res::Err(55), add_34),
];

assert_eq!(ARR, &[3, 13, 21, 89]);

const fn add_34(n: u32) -> u32 {
    n + 34
}