[][src]Macro ward::ward

macro_rules! ward {
    ($o:expr) => { ... };
    ($o:expr, else $body:block) => { ... };
    ($o:expr, $early:stmt) => { ... };
}

Returns the contents of a Option<T>'s Some(T), otherwise it returns early from the function. Can alternatively have an else branch, or an alternative "early return" statement, like break or continue for loops, e.g.

Examples

// res is set to sut's contents when sut is Some(...)
let sut = Some("test");
let res = ward!(sut);
assert_eq!(res, "test");
// When sut is None, the ward! returns early
let sut = None;
let res = ward!(sut);
unreachable!();
// Because sut is None, the else branch will be run. When the else branch is invoked, ward!
// no longer automatically returns early for you, so you must do so yourself if you want it.
let sut = None;
let _res = ward!(sut, else {
    println!("This code will run!");
    return;
});
unreachable!();
// The lack of automatic early return for the else branch allows for alternative return values
// to be provided.
let sut = None;
let res = ward!(sut, else { 42 });
assert_eq!(res, 42);
// You can use ward! with a different "early return" statement, such as break for loops
let mut sut = Some(0);
loop {
    let res = ward!(sut, break);
    sut = if res < 5 {
        Some(res + 1)
    } else {
        None
    }
}
assert_eq!(sut, None);
// Unlike guard!, ward! can be used as an expression
let sut = Some("test");
print(ward!(sut));

fn print(text: &str) {
    println!("{}", text);
}