macro_rules! require_with {
    ($expr: expr, $fmt:literal) => { ... };
    ($expr: expr, $str: expr) => { ... };
    ($expr: expr, $fmt:literal, $($arg:tt)+) => { ... };
}
Expand description

Helper macro for unwrapping Option values while returning early with a newly constructed SimpleError if the value of the expression is None. Can only be used in functions that return Result<_, SimpleError>.

Examples

use self::simple_error::SimpleError;
use std::error::Error;

fn require_block(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
    Ok(require_with!(maybe, s))
}

// Above is equivalent to below.

fn require_block_equivalent(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
    match maybe {
        Some(v) => Ok(v),
        None => {
            return Err(SimpleError::new(s));
        },
    }
}

// Use a format string

fn require_block_format(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
    Ok(require_with!(maybe, "with {}", s))
}

// Use a format string to a boxed error

fn require_block_format_to_box_error(maybe: Option<()>, s: &str) -> Result<(), Box<dyn Error>> {
    Ok(require_with!(maybe, "with {}", s))
}