Declarative macro rules
Quick answer
A declarative macro matches input tokens against rules and expands the first matching rule. Use one when syntax-level repetition cannot be expressed as an ordinary function.
Matcher and transcriber
macro_rules! name { (pattern) => { expansion }; } defines a rule. A metavariable such as $value:expr matches an expression; $value inserts it into the expansion. Rules are tried in order, and the generated tokens must be valid in their use context. Unlike a function, a macro may duplicate evaluation if it inserts an expression repeatedly.
macro_rules! triple { ($x:expr) => { 3 * ($x) }; }fn main() { println!("{}", triple!(2 + 3)); }Expected stdout (not executed):
15Parentheses preserve the expression grouping.
macro_rules! square_once { ($x:expr) => {{ let value = $x; value * value }}; }fn main() { let mut n = 0; let result = square_once!({ n += 1; n + 2 }); println!("{result} {n}");}Expected stdout (not executed):
9 1A local binding avoids evaluating the argument twice.
Common mistake
Prefer ordinary functions when typed values are sufficient.
Try it yourself
Create a macro that evaluates an expression once and adds ten; compare it to a function.
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
Declarative macro rules — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A macro expands an argument expression twice. How can you avoid repeating side effects?
Declarative macro rules — 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! triple { ($x:expr) => { 3 * ($x) }; } fn main() { println!("{}", triple!(2 + 3)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Declarative macro rules — 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! square_once { ($x:expr) => {{ let value = $x; value * value }}; } fn main() { let mut n = 0; let result = square_once!({ n += 1; n + 2 }); println!("{result} {n}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.