Macro const_panic::unwrap_some

source ·
macro_rules! unwrap_some {
    ($opt:expr) => { ... };
}
Expand description

Gets the value in the Some variant.

§Panics

Panics if $opt is a None.

§Example

use const_panic::unwrap_some;

const SUM: u8 = unwrap_some!(add_up(&[3, 5, 8, 13]));

assert_eq!(SUM, 29);


const fn add_up(mut slice: &[u8]) -> Option<u8> {
    let mut sum = 0u8;
     
    while let [x, ref rem @ ..] = *slice {
        match sum.checked_add(x) {
            Some(x) => sum = x,
            None => return None,
        }
        slice = rem;
    }
     
    Some(sum)
}

§Error

This is what the compile-time error looks like when attempting to unwrap a None:

error[E0080]: evaluation of constant value failed
 --> src/macros/unwrapping.rs:10:17
  |
6 | const SUM: u8 = unwrap_some!(add_up(&[3, 5, 8, 13, 250]));
  |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
invoked `unwrap_some` macro with a `None` value', src/macros/unwrapping.rs:6:17
  |
  = note: this error originates in the macro `unwrap_some` (in Nightly builds, run with -Z macro-backtrace for more info)