How do I create a Rust macro with optional parameters using repetitions?

13,707

NOTE: Since this answer was written, Rust has gained the ability to express optional elements in a pattern (stabilized in Rust 1.32.0) using the syntax $(tokens)?.

The first edition of the Rust book has a rather long chapter on macros, but the section on repetitions is a bit shy on examples...

There are several ways to handle optional arguments in macros. If you have an optional argument that can only occur once, then you shouldn't use repetitions: you should instead define multiple patterns in your macro, like this:

macro_rules! single_opt {
    ($mand_1:expr, $mand_2:expr) => {
        single_opt!($mand_1, $mand_2, "Default")
    };
    ($mand_1:expr, $mand_2:expr, $opt:expr) => {
        println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, $opt)
    };
}

fn main() {
    single_opt!(4, 4);
}

If you want to allow an arbitrary number of arguments, then you need repetition. Your original macro doesn't work because you put the comma outside the repetition, so you'd have to invoke the macro as single_opt!(4,4,);. See How to allow optional trailing commas in macros? for a related case.

If you have a fixed number of arguments followed by a repetition, you can put the comma inside the repetition as the first token:

macro_rules! single_opt {
    ($mand_1:expr, $mand_2:expr $(, $opt:expr)*) => {
        println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, $($opt),*)
    };
}

However, it doesn't work in this specific case:

error: 3 positional arguments in format string, but there are 2 arguments
 --> src/main.rs:3:22
  |
3 |         println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, $($opt),*)
  |                      ^^    ^^     ^^
...
8 |     single_opt!(4, 4);
  |     ------------------
  |     |
  |     in this macro invocation
  |     in this macro invocation
  |     in this macro invocation
  |
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

So we'll have to go back to defining two patterns:

macro_rules! single_opt {
    ($mand_1:expr, $mand_2:expr) => {
        single_opt!($mand_1, $mand_2, "Default")
    };
    ($mand_1:expr, $mand_2:expr, $($opt:expr),*) => {
        {
            println!("1. {} 2. {}", $mand_1, $mand_2);
            $(
                println!("opt. {}", $opt);
            )*
        }
    };
}

fn main() {
    single_opt!(4, 4, 1, 2);
}

A repetition takes the form $( PATTERN ) SEPARATOR COUNT, where PATTERN is the pattern you want to repeat, SEPARATOR is an optional token that separates each repetition (here, it's ,) and COUNT is either * for "zero or more occurrences" or + for "one or more occurrences".

Then, in the macro expansion, we need a repetition block to be able to access $opt. The syntax is exactly the same, but note that the separator doesn't have to be the same (here, there's no separator in the expansion).

Share:
13,707
Stein
Author by

Stein

I am currently a physics student at LMU University in Munich.

Updated on June 04, 2022

Comments

  • Stein
    Stein almost 2 years

    I'm currently looking into Rust macros and I can not find any detailed documentation on repetitions. I would like to create macros with optional parameters. This would be my idea:

    macro_rules! single_opt {
        ($mand_1, $mand_2, $($opt:expr)* ) =>{
            match $opt {
                Some(x) => println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, x);
                None => single_opt!($mand_1, $mand_2, "Default");
            }
        }
    }
    
    fn main() {
        single_opt!(4,4);
    }
    

    This example seems to be outdated, since I can not compile it. The Rust book mentions this topic just very briefly. How do I get this example to work?