Level 3 · Systems· Lesson 5 of 11 · 25 min
Declarative macros
macro_rules! — pattern-matching on syntax, repetition, hygiene, and when a macro is the right tool.
What macros are for
Functions abstract over values. Generics abstract over types. Macros abstract over syntax: they take tokens and produce code, before type checking. Use them for what the other two cannot do — variadic arguments, new syntax, generating repetitive items — and prefer a function or a generic whenever one would work.
macro_rules!
A declarative macro is a list of rules, (pattern) => { expansion }, tried in order.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
macro_rules! maximum {
($x:expr) => { $x };
($x:expr, $($rest:expr),+) => {{
let a = $x;
let b = maximum!($($rest),+); // recursion
if a > b { a } else { b }
}};
}
fn main() {
println!("{}", square!(7));
println!("{}", square!(2 + 3)); // 25, not 11: an `expr` fragment stays one unit
println!("{}", maximum!(3, 9, 4, 1));
}
$x:expr captures an expression. Unlike a C macro, the capture is a parsed syntax tree, not text, so square!(2 + 3) is (2 + 3) * (2 + 3). (It still evaluates the argument twice — bind it to a local if that matters, as maximum! does.)
Fragment specifiers
| Specifier | Matches |
|---|---|
expr |
an expression |
ident |
an identifier |
ty |
a type |
pat |
a pattern |
stmt |
a statement |
block |
a { … } block |
item |
an item: fn, struct, impl… |
path |
a path such as std::fmt::Debug |
literal |
a literal |
lifetime |
a lifetime |
vis |
a visibility qualifier, possibly empty |
meta |
the inside of an attribute |
tt |
a single token tree — the most flexible |
Repetition
use std::collections::HashMap;
macro_rules! hashmap {
() => { HashMap::new() };
( $( $key:expr => $value:expr ),+ $(,)? ) => {{
let mut map = HashMap::new();
$( map.insert($key, $value); )+
map
}};
}
fn main() {
let ages = hashmap! {
"Ada" => 36,
"Grace" => 85, // trailing comma accepted thanks to $(,)?
};
let empty: HashMap<u8, u8> = hashmap!();
println!("{:?} {}", ages.get("Ada"), empty.len());
}
$( … ),+ matches the inner pattern one or more times, comma-separated. In the expansion, $( … )+ repeats its body once per match. The double braces {{ … }} make the expansion a single block expression.
Generating items
Macros shine at eliminating boilerplate impls:
trait Zero {
fn zero() -> Self;
fn is_zero(&self) -> bool;
}
macro_rules! impl_zero {
($($t:ty => $z:expr),* $(,)?) => {
$(
impl Zero for $t {
fn zero() -> Self { $z }
fn is_zero(&self) -> bool { *self == $z }
}
)*
};
}
impl_zero!(u8 => 0, i32 => 0, u64 => 0, f64 => 0.0);
macro_rules! newtype {
($(#[$meta:meta])* $vis:vis struct $name:ident($inner:ty);) => {
$(#[$meta])*
$vis struct $name($inner);
impl From<$inner> for $name {
fn from(v: $inner) -> Self { $name(v) }
}
impl std::ops::Deref for $name {
type Target = $inner;
fn deref(&self) -> &$inner { &self.0 }
}
};
}
newtype! {
/// A user identifier.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct UserId(u64);
}
fn main() {
println!("{} {}", i32::zero().is_zero(), 2.5f64.is_zero());
let id: UserId = 42.into();
println!("{id:?} {}", *id + 1);
}
This is how the standard library implements traits for all the integer types.
Hygiene
macro_rules! swap {
($a:expr, $b:expr) => {
let tmp = $a;
$a = $b;
$b = tmp;
};
}
fn main() {
let mut tmp = 1; // same name as the macro's internal variable
let mut other = 2;
swap!(tmp, other);
println!("{tmp} {other}"); // 2 1 — no collision
}
The tmp inside the macro and the caller’s tmp are different identifiers: macro_rules! is hygienic for local variables and labels. It is not hygienic for items and paths, which resolve at the call site. Therefore, in a library, refer to your own items as $crate::path::Item and to std items by absolute path (::std::vec::Vec).
Scoping and export
Within a crate a macro is visible textually after its definition. #[macro_export] places it at the crate root for other crates to use. In modern code you can also re-export it by path with pub(crate) use my_macro;.
Debugging
cargo expand(a cargo subcommand you install) prints your code with all macros expanded.- The compiler’s errors point into the expansion and name the macro.
- For complex input, the tt-muncher pattern processes one token tree at a time recursively, and internal rules (
(@step …) => …) keep helper arms private. The Little Book of Rust Macros catalogues these techniques.
Limits
macro_rules! cannot inspect types, compute with values, or create new identifiers by concatenation. When you need to parse a whole struct definition and generate code from its fields, you need a procedural macro — the next lesson.
Exercises
- Write
my_vec!supportingmy_vec![],my_vec![1, 2, 3], andmy_vec![0; 5]. - Write
count!(a, b, c)that expands to the number of arguments as ausizeconstant expression. - Write a macro
enum_str!that defines an enum and anas_str(&self) -> &'static strmethod returning each variant’s name (hint:stringify!).
Solution to 3
macro_rules! enum_str {
($vis:vis enum $name:ident { $($variant:ident),+ $(,)? }) => {
#[derive(Debug, Clone, Copy, PartialEq)]
$vis enum $name { $($variant),+ }
impl $name {
$vis fn as_str(&self) -> &'static str {
match self {
$( $name::$variant => stringify!($variant), )+
}
}
}
};
}
enum_str! { pub enum Level { Debug, Info, Warn } }
fn main() {
println!("{} {}", Level::Info.as_str(), Level::Warn.as_str());
}
Check your understanding
Pick an answer to see the explanation.
1.What does
$( $x:expr ),*match?2.What does macro hygiene guarantee for
macro_rules!?3.Why is
vec!a macro and not a function?