Crate check

Source
Expand description

Convenience assert!-like macros which immediately returns None or Err(...) instead of panicking.

§Examples

In a function returning an Option<T>, invoke the macro with just enough parameters to get a condition to check.

check!(a < n);
check_eq!(a, b);

This will expand to:

if !(a < n) {
  return None;
}
if a != b {
  return None;
}

In a function returning a Result<T, E>, invoke the macro with an extra argument, which is the error to return if the check fails (and must have type E), just like you can add arguments to choose a panic message with assert!.

check!(a < n, MyError::TooBig);
check_eq!(a, b, MyError::NotEqual);

This will expand to:

if !(a < n) {
  return Err(MyError::TooBig);
}
if a != b {
  return Err(MyError::NotEqual);
}

§Note

Actually, the two following lines are quite equivalent:

check!(a <= b);
(a <= b).then(|| ())?;

Macros§

check
Exits the function prematurely if the condition is not met.
check_eq
Exits the function prematurely if the two expressions do not evaluate the same.
check_ne
Exits the function prematurely if the two expressions evaluate the same.