Sub topic 1
Why Rust Macros Exist and How They Differ from Functions
Prerequisites
This chapter assumes basic Rust syntax, including functions, expressions, types, let bindings, and println!. You should also know how to build and run a Cargo project.
Why Macros Exist
A function receives values at runtime. A declarative macro receives Rust syntax and generates Rust syntax at compile time. This lets a macro accept patterns that a function cannot, such as a variable number of arguments, type definitions, or custom keywords.
Use a function when the operation has a stable input and output type. Use macro_rules! when the caller's syntax must vary or when repeated code should be generated.
Your First `macro_rules!` Macro
A macro_rules! macro contains one or more rules. Each rule has a matcher, which describes accepted syntax, and a transcriber, which produces replacement syntax.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}The expr fragment matches one Rust expression. The macro expands before normal compilation, and the compiler then checks the generated expression. The program prints 25.
Writing Rules: Matchers and Multiple Arms
A macro can have several arms. Rust tries them in order and uses the first matching arm.
macro_rules! describe {
() => {
"nothing"
};
($value:expr) => {
"one value"
};
}
fn main() {
println!("{}", describe!());
println!("{}", describe!(42));
}The empty invocation matches the first arm. The invocation containing 42 matches the second arm.
Fragment Specifiers
A fragment specifier controls what a metavariable can match.
| Specifier | Matches |
|---|---|
| `expr` | An expression, such as `a + 1` |
| `ident` | An identifier, such as `name` |
| `ty` | A type, such as `Vec<i32>` |
| `tt` | One token tree, including grouped tokens |
| `item` | An item, such as a function or struct |
| `pat` | A pattern |
| `block` | A braced block |
Use the narrowest suitable fragment. expr communicates that an expression is expected, while tt accepts much broader syntax and is useful for recursive token processing.
Exercise
Which fragment specifier should match a caller-provided variable name?
Show answer
Use ident, as in ($name:ident).