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:
  1. #![allow(unused_variables)]
  2. fn main() {
  3. macro_rules! foo {
  4. ($a:ident, $b:expr) => {
  5. println!("{}", $a);
  6. println!("{}", $b);
  7. };
  8. ($a:ident) => {
  9. println!("{}", $a);
  10. }
  11. }
  12. }

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:

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