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).