[][src]Macro ward::guard

macro_rules! guard {
    (let $result:ident = $o:expr) => { ... };
    (let $result:ident = $o:expr, else $body:block) => { ... };
    (let $result:ident = $o:expr, $early:stmt) => { ... };
    (let mut $result:ident = $o:expr) => { ... };
    (let mut $result:ident = $o:expr, else $body:block) => { ... };
    (let mut $result:ident = $o:expr, $early:stmt) => { ... };
}

Creates a variable with 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");
guard!(let res = sut);
assert_eq!(res, "test");
// When sut is None, the guard! returns early
let sut = None;
guard!(let mut res = sut);
unreachable!();
// Because sut is None, the else branch will be run. When the else branch is invoked, guard!
// no longer automatically returns early for you, so you must do so yourself if you want it.
let sut = None;
guard!(let _res = 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;
guard!(let res = sut, else { 42 });
assert_eq!(res, 42);
// You can use guard! with a different "early return" statement, such as break for loops
let mut sut = Some(0);
loop {
    guard!(let res = sut, break);
    sut = if res < 5 {
        Some(res + 1)
    } else {
        None
    }
}
assert_eq!(sut, None);