macro_rules! or_else { ($res:expr, |$param:pat_param| $expr:expr $(,)?) => { ... }; ($opt:expr, | $($anything:tt)* ) => { ... }; ($res:expr, $function:expr $(,)?) => { ... }; }
Expand description
A const equivalent of Result::or_else
§Example
use konst::result;
// Necessary for type inference reasons.
type Res = Result<u32, u32>;
const ARR: &[Res] = &[
// 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::or_else!(Res::Ok(1), |_| loop{}),
result::or_else!(Res::Err(20), |x| Ok(x + 5)),
result::or_else!(Res::Err(20), |x| Err(x + 7)),
// You can also pass functions
result::or_else!(Res::Ok(40), add_2),
result::or_else!(Res::Err(60), add_2),
result::or_else!(Res::Err(60), add_5),
];
assert_eq!(ARR, &[Ok(1), Ok(25), Err(27), Ok(40), Ok(62), Err(65)]);
const fn add_2(n: u32) -> Res {
Ok(n + 2)
}
const fn add_5(n: u32) -> Res {
Err(n + 5)
}