guard

Macro guard 

Source
macro_rules! guard {
    ($check:expr, $fail_return:expr) => { ... };
    ($check:expr) => { ... };
}
Expand description

Checks that a boolean expression is true at runtime, otherwise performs a return with the second parameter, short-circuiting the operation of the enclosing function.

§Uses

Guard clauses are used, generally at the start of functions, to ensure that conditions are valid for the operation of the function. The usage is similar to an assertion, but the guard clause returns a value that may be evaluated and acted on by the calling function, while assertions end the program by panicking.

The guard macro is syntactic sugar that replaces an if clause that would return when true. The guard macro can be written on one line, while the default Rust code formatter expands any if clause to three lines.

§Examples

§Guard returning on Option

use guard_clause::guard;

fn safe_divide_using_option(lval: i32, rval: i32) -> Option<i32> {
    guard!(rval != 0, None);
    Some(lval / rval)
}
assert_eq!(Some(3), safe_divide_using_option(6, 2));
assert_eq!(None, safe_divide_using_option(6, 0));

§Guard returning a string

use guard_clause::guard;

fn safe_divide_using_result_str(lval: i32, rval: i32) -> Result<i32, &'static str> {
    guard!(rval != 0, Err("Divide by zero!"));
    Ok(lval / rval)
}
assert_eq!(Ok(3), safe_divide_using_result_str(6, 2));
assert_eq!(Err("Divide by zero!"), safe_divide_using_result_str(6, 0));

§Guard returning a enum

use guard_clause::guard;

#[derive(Debug, PartialEq)]
enum DivError {
    DivideByZero
}
fn safe_divide_using_result_enum(lval: i32, rval: i32) -> Result<i32, DivError> {
    guard!(rval != 0, Err(DivError::DivideByZero));
    Ok(lval / rval)
}
assert_eq!(Ok(3), safe_divide_using_result_enum(6, 2));
assert_eq!(Err(DivError::DivideByZero), safe_divide_using_result_enum(6, 0));

§Guard returning the unit type: ‘()’

use guard_clause::guard;
fn increments_if_zero(i: &mut i32) {
    guard!(*i == 0);
    *i += 1;
}

let mut i = 0;
increments_if_zero(&mut i);
assert_eq!(1, i);

let mut j = 2;
increments_if_zero(&mut j);
assert_eq!(2, j);