4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Optional arguments in Rust macro definition

Last updated at Posted at 2020-10-10

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.

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?