Macro extract

Source
macro_rules! extract {
    ($nr:expr) => { ... };
    ($nr:expr, $err:ty) => { ... };
}
Expand description

This macro extract that works like the ? operator and can be used in functions that return a NullableResult as long as the error type is the same. It takes a NullableResult, a Result, or an Option. If the input contains an Ok or Some value, the value is extracted and returned, if it contains an Err or Null, the function returns early with the Err or Null wrapped in a new NullableResult.

fn do_a_thing() -> NullableResult<usize, isize> {
    let res = some_other_func();
    let number = extract!(res); // <---- this will cause the function to return early
    NullableResult::Ok(number as usize + 5)
}

// note that the two functions have different types for their Ok values
fn some_other_func() -> NullableResult<i8, isize> {
    NullableResult::Null
}

If the input is an option, it requires a second parameter as a type annotation for converting to a [’NullableResult`]. Hopefully this won’t be necessary in some future version.

fn f() -> NullableResult<usize, isize> {
    let opt = Some(4_usize);
    let four = extract!(opt, isize);
    NullableResult::Ok(four)
}