macro_rules! unwrap_ok {
($res:expr) => { ... };
}
Expand description
Gets the value in the Ok
variant.
§Panics
This panics if $res
is an Err
, including the debug-formatted error in the panic message.
§Example
The struct formatting below requires the "non_basic"
feature (enabled by default)
ⓘ
use const_panic::unwrap_ok;
const SUM: u64 = unwrap_ok!(add_up_evens(&[2, 4, 8, 16]));
assert_eq!(SUM, 30);
const fn add_up_evens(slice: &[u8]) -> Result<u64, OddError> {
let mut sum = 0u64;
let mut i = 0;
while i < slice.len() {
let x = slice[i];
if x % 2 == 1 {
return Err(OddError{at: i, number: x});
}
sum += x as u64;
i += 1;
}
Ok(sum)
}
struct OddError {
at: usize,
number: u8,
}
// You can also use `#[derive(PanicFmt))]` with the "derive" feature
const_panic::impl_panicfmt!{
struct OddError {
at: usize,
number: u8,
}
}
§Error
This is what the compile-time error looks like when attempting to unwrap an Err
:
error[E0080]: evaluation of constant value failed
--> src/macros/unwrapping.rs:51:18
|
6 | const SUM: u64 = unwrap_ok!(add_up_evens(&[3, 5, 8, 13]));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
invoked `unwrap_ok` macro with an `Err` value: OddError { at: 0, number: 3 }', src/macros/unwrapping.rs:6:18
|