Repetition and hygiene
Quick answer
Macro repetition matches a variable number of tokens. Hygiene controls which identifiers refer to definitions at the call site and which refer to the macro definition site.
Repeat token groups safely
$( $x:expr ),* matches zero or more comma-separated expressions. + requires at least one; ? matches zero or one and cannot have a repetition separator. $(,)? allows an optional trailing comma. Declarative macros have mixed-site hygiene: local variables and labels resolve at definition site, other names generally at invocation site. $crate helps exported macros refer to their defining crate.
macro_rules! total { ($($x:expr),* $(,)?) => { 0 $(+ ($x))* }; }fn main() { println!("{} {}", total!(2, 4, 6,), total!()); }Expected stdout (not executed):
12 0The zero seed handles empty input.
macro_rules! twice { ($e:expr) => {{ let tmp = $e; tmp + tmp }}; }fn main() { let tmp = 5; println!("{} {}", twice!(tmp + 1), tmp); }Expected stdout (not executed):
12 5The generated tmp binding does not replace the caller's tmp.
Common mistake
Do not assume macro-local variables can be accessed by name from the caller.
Try it yourself
Modify total to require one or more expressions and check that an empty call is rejected.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Repetition and hygiene — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A macro should accept a list with an optional trailing comma. Which pattern component represents that optional comma?
Repetition and hygiene — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust macro_rules! total { ($($x:expr),* $(,)?) => { 0 $(+ ($x))* }; } fn main() { println!("{} {}", total!(2, 4, 6,), total!()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Repetition and hygiene — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust macro_rules! twice { ($e:expr) => {{ let tmp = $e; tmp + tmp }}; } fn main() { let tmp = 5; println!("{} {}", twice!(tmp + 1), tmp); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.