#macro #error #error-message #assert #return #returning #condition

check

Convenience assert!-like macros which return instead of panicking

1 stable release

1.0.0 Mar 17, 2022
0.1.0 May 7, 2017

#1718 in Rust patterns


Used in divisibility_check

MIT/Apache

8KB
89 lines

Check

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

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);
}

lib.rs:

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(|| ())?;

No runtime deps