Here is a simple example that showing a rust macro that accept optional arguments(arguments number is not fixed/variable arguments)
macro_rules! foo {
($var:ident $(, $check:expr )?) => {
let val = $var;
let mut ok = true;
$ ( ok = $check(val); )?
if ok {
println!("var is: {}", val);
}
};
}
fn main() {
let x = 10;
let y = 20;
foo!(x, |v| v > 10);
foo!(y, |v| v > 10);
}
First, the ($var:ident $(, $check:expr )?)
is pattern matching part of a macro.
?
in $(, $check:expr )?
means the $check
has zero or one occurrences.
The repetition operators are:
-
*
— indicates any number of repetitions. -
+
— indicates any number but at least one. -
?
— indicates an optional fragment with zero or one occurrences.
Next, $ ( ok = $check(val); )?
is in format $( xxx )?
, means that the statement will execute zero or one time.