macro_rules! and_then {
($res:expr, |$param:pat| $expr:expr $(,)?) => { ... };
($opt:expr, | $($anything:tt)* ) => { ... };
($res:expr, $function:expr $(,)?) => { ... };
}
Expand description
A const equivalent of Result::and_then
ยง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 Ok.
// `return` inside the "closure" returns from the function where this macro is called.
result::and_then!(Res::Ok(1), |x| Ok(x + 2)),
result::and_then!(Res::Ok(10), |x| Err(x + 4)),
result::and_then!(Res::Err(20), |_| loop{}),
// You can also pass functions
result::and_then!(Res::Ok(40), add_2),
result::and_then!(Res::Ok(40), add_5),
result::and_then!(Res::Err(60), add_5),
];
assert_eq!(ARR, &[Ok(3), Err(14), Err(20), Ok(42), Err(45), Err(60)]);
const fn add_2(n: u32) -> Res {
Ok(n + 2)
}
const fn add_5(n: u32) -> Res {
Err(n + 5)
}