Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Macro repetitions

Reference for repetitions in Rust macro_rules!: the *, + and ? operators, separators, trailing commas, nested repetitions and how captures expand.

Repetitions let a macro_rules! rule accept any number of similar items. The form is $( ... ) separator? operator, where the operator is * (zero or more), + (one or more) or ? (zero or one). The optional separator is a single token such as , or ; that must appear between repetitions.

A variable captured inside a repetition must be used inside a repetition in the expansion, with the same depth. The expansion repeats once per captured item.

Rust
($($x:expr),* $(,)?) => { [$($x),*] };

Try it

Rust Counting and summing a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Nested repetitions and a map literal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
$( pattern ) separator operator      // in a matcher
$( template ) separator operator     // in an expansion
Operator Meaning
* Zero or more repetitions.
+ One or more repetitions.
? Zero or one repetition (no separator allowed).
separator One token (not *, + or ?) placed between repetitions, such as , or ;.

Usage notes

  • Separators go between items, not after. To allow a trailing comma add $(,)?, as in the examples.
  • Matching depth must agree. A capture made inside one $(...)* can only be expanded inside one $(...)*; nested captures need nested repetitions.
  • Several variables in one repetition advance together and must have the same count, otherwise the compiler reports a mismatch.
  • No counting built in. Count with recursion (as above), with [$(replace!($x ())),*].len() tricks, or by building an array and taking its length.
  • Ambiguity. The parser cannot look ahead. A pattern like $($x:expr),* , $last:expr is rejected; restructure with $first, $($rest),*.
  • Recursion depth. Counting macros recurse once per item; the default recursion limit is 128.
  • ? repetition is the usual way to make a part optional, for example $(, $name:ident)?.