November 2017
Intermediate to advanced
264 pages
5h 45m
English
In the following macro, massert, we mimic the behavior of the assert! macro, which does nothing when its expression argument is true, but panics when it is false:
macro_rules! massert {
($arg:expr) => (
if $arg {}
else { panic!("Assertion failed!"); }
);
}
For example: massert!(1 == 42); will print out:
thread '<main>' panicked at 'Assertion failed!'
In the following statements, we test whether vector v contains certain elements:
let v = [10, 40, 30];
massert!(v.contains(&30));
massert!(!v.contains(&50));
The macro unless mimics an unless statement, where a branch is executed if the arg condition is not true. For example:
unless!(v.contains(&25), println!("v does not contain 25"));
It should print out:
v does not ...
Read now
Unlock full access