Write declarative macros in Rust with macro_rules!
8 steps · about 1 h 58 min · Intermediate
- Compare declarative and procedural macros (guide, The Rust Programming Language, 20 min)
The Book explains when a macro beats a function and how macro_rules! matching works.
- Write your first macro_rules! macro (guide, Rust by Example, 8 min)
A tiny runnable example shows the shape of a macro definition and call.
- Capture expressions and identifiers with fragment specifiers (guide, Rust by Example, 10 min)
Shows how expr, ident, ty and other designators control what a macro accepts.
- Accept a variable number of arguments with repetition (tutorial, Rust by Example, 10 min)
Practises the $(...),* pattern that powers macros like vec!.
- Build a tiny calculator DSL with a macro (tutorial, Rust by Example, 10 min)
Turns matching rules into a small domain-specific syntax you can extend.
- Check the exact matching and follow-set rules (reference, The Rust Reference, 25 min)
The reference settles why a matcher is ambiguous or rejected by the compiler.
- Work through macro expansion step by step (guide, The Little Book of Rust Macros, 25 min)
Explains token trees and expansion order, the root of most confusing macro errors.
- Inspect expanded code with cargo expand (repo, David Tolnay, 10 min)
Lets you see exactly what your macro generated when debugging.