At most one repetition

Minimum Rust version: 1.32 for 2018 edition

Minimum Rust version: 1.37 for 2015 edition

In Rust 2018, we have made a couple of changes to the macros-by-example syntax.

  • We have added a new Kleene operator ? which means "at most one"repetition. This operator does not accept a separator token.
  • We have disallowed using ? as a separator to remove ambiguity with ?.For example, consider the following Rust 2015 code:
2. #![allow(unused_variables)]
3. fn main() {
4. macro_rules! foo {
5. ($a:ident, $b:expr) => {
6. println!("{}", $a);
7. println!("{}", $b);
8. };
9. ($a:ident) => {
10. println!("{}", $a);
11. }
12. }
13. }

Macro foo can be called with 1 or 2 arguments; the second one is optional,but you need a whole other matcher to represent this possibility. This isannoying if your matchers are long. In Rust 2018, one can simply write thefollowing:

2. #![allow(unused_variables)]
3. fn main() {
4. macro_rules! foo {
5. ($a:ident $(, $b:expr)?) => {
6. println!("{}", $a);

8. $(
9. println!("{}", $b);
10. )?
11. }
12. }
13. }