macro_rules! unwrap_ctx {
($e:expr $(,)?) => { ... };
}
Expand description
For unwrapping Result
s in const contexts with some error message.
The error type must have a method with this signature:
pub const fn panic(&self) -> ! {
All the errors from this crate can be used with this macro.
§Example
§Basic
use konst::{Parser, unwrap_ctx};
let mut parser = Parser::new("hello world");
parser = unwrap_ctx!(parser.strip_prefix("hello "));
assert_eq!(parser.remainder(), "world");
§Defining error type
use konst::unwrap_ctx;
const UNWRAPPED: u32 = {
let res: Result<u32, FooError> = Ok(100);
unwrap_ctx!(res)
};
assert_eq!(UNWRAPPED, 100);
use std::fmt::{self, Display};
#[derive(Debug, Clone, PartialEq)]
pub struct FooError(usize);
impl FooError {
pub const fn panic(&self) -> ! {
panic!("Foo error")
// Alternatively, using the `const_panic` crate:
//
// const_panic::concat_panic!("Foo errored at offset: ", self.0)
}
}
impl Display for FooError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for FooError {}
If res
was an error instead, this is the error message you would see:
error[E0080]: evaluation of constant value failed
--> src/result.rs:55:9
|
9 | unwrap_ctx!(res)
| ---------------- inside `UNWRAPPED` at result_macros_.rs:6:35
...
23 | panic!("Foo error")
| ^^^^^^^^^^^^^^^^^^^
| |
| the evaluated program panicked at 'Foo error', src/result.rs:23:9
| inside `FooError::panic`