Sub topic 1
Why macros exist and how they differ from functions
Prerequisites
This chapter assumes you can:
- Write Rust functions,
letbindings, structs, and closures. - Call
println!andvec!and read their output. - Build and run a small project with Cargo, or paste a single
main.rsinto the Rust Playground. - Recognize an expression, a type, and an identifier in Rust source.
You don't need to have written a macro before. This chapter builds the mental model that the rest of the tutorial uses.
The problem functions cannot solve
Functions are the default tool for reuse in Rust. A function has a fixed signature, its arguments are values with known types, and the compiler checks every call against that signature. Those same rules make some jobs impossible.
Consider println!. These calls are all valid:
fn main() {
println!("hello");
println!("{}", 1);
println!("{} and {:?}", "text", Some(3));
}A function cannot do this, for three reasons:
- Rust functions have a fixed number of parameters, and these calls pass one, two, and three arguments.
- A function would need one type for each argument, but here the types differ.
- The format string is checked at compile time. A mismatch between
{}placeholders and arguments is a compile error, not a runtime panic.
println! is a macro. A macro is code that the compiler runs during compilation. It receives the source tokens you wrote and produces new source code in their place. The compiler then continues with the produced code as if you had typed it.
This tutorial covers declarative macros, which you define with macro_rules!. A declarative macro works by pattern matching: you describe the shapes of input you accept, and for each shape you describe the code to produce.
Where expansion happens
A function call survives to the compiled program. A macro call does not. It is replaced during compilation, so by the time the compiler type-checks your program, the macro invocation is gone.
Two consequences follow from this ordering:
- The macro input does not need to be valid Rust in the usual sense. It must be a sequence of tokens that the macro's patterns accept, and the expanded output must be valid Rust. This is why a macro can accept
$k => $vpairs, which are not a Rust expression. - Type errors are reported against the expanded code. A mistake in a macro's output can produce an error that points at the invocation site, not at a line you can read in the macro body.
A first comparison
Here is the smallest useful macro. It takes one expression and multiplies it by itself:
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}This prints 25. The matcher $x:expr tells the compiler to parse the argument as one complete expression, so 2 + 3 stays grouped. The expansion behaves like (2 + 3) * (2 + 3).
This differs from the C preprocessor, which pastes text. A text-based SQUARE(2 + 3) becomes 2 + 3 * 2 + 3, which is 11. Rust macros operate on parsed fragments, not raw text, so an expr fragment keeps its grouping.
The macro matched syntax, not a value. A function version would receive the already-computed 5:
fn square_fn(x: i32) -> i32 {
x * x
}For this example the two behave the same. The next sections show where they diverge.
Differences that matter in practice
| Aspect | Function | `macro_rules!` macro |
|---|---|---|
| Called with | `name(args)` | `name!(args)`, `name![args]`, or `name!{args}` |
| Number of arguments | Fixed by the signature | Any number your patterns accept |
| Argument types | Declared and checked at the call | None declared. Fragments such as `expr` or `ident` describe syntax |
| When arguments are evaluated | Once, before the body runs | Whenever the expanded code evaluates them, possibly several times or never |
| Runs at | Runtime | Compile time (the expansion), then the output runs at runtime |
| Can produce items (structs, impls, functions) | No | Yes |
| Can return from the caller | No | Yes, because the expansion is inline in the caller |
| Error messages | Point at the call and the signature | Point at the invocation, often with less specific text |
Arguments can be evaluated more than once
A function argument is evaluated once and then passed in. A macro pastes the argument expression wherever $e appears, so side effects repeat:
macro_rules! double_macro {
($e:expr) => {
$e + $e
};
}
fn double_fn(x: i32) -> i32 {
x + x
}
fn main() {
let mut calls = 0;
let mut next = || {
calls += 1;
calls
};
let a = double_fn(next());
let b = double_macro!(next());
println!("{} {}", a, b);
}This prints 2 5. double_fn(next()) calls next() once and gets 1, so a is 1 + 1 = 2. double_macro!(next()) expands to next() + next(), which yields 2 + 3 = 5.
The usual fix is to bind the argument to a local variable inside the expansion:
macro_rules! double_once {
($e:expr) => {{
let value = $e;
value + value
}};
}
fn main() {
let mut calls = 0;
let mut next = || {
calls += 1;
calls
};
println!("{}", double_once!(next()));
}This prints 2. The double braces matter: the outer pair belongs to the macro syntax, and the inner pair makes the expansion a block expression that can contain a let.
Macros accept a variable number of inputs
One macro can have several rules, each matching a different shape of input. The compiler tries them in order and uses the first that matches:
macro_rules! largest {
($a:expr) => {
$a
};
($a:expr, $b:expr) => {{
let a = $a;
let b = $b;
if a > b { a } else { b }
}};
}
fn main() {
println!("{}", largest!(7));
println!("{}", largest!(3, 9));
println!("{}", largest!("pear", "apple"));
}This prints 7, 9, and pear. The third call works because the macro never declares a type. Each expansion is type-checked on its own, and &str supports >. A function would need a generic parameter with a PartialOrd bound, and it still could not take one argument in one call and two in another.
A call with three arguments, such as largest!(1, 2, 3), fails with no rules expected the token. No rule matches that shape. Later chapters add repetitions so that one rule covers any count.
Macros can change the control flow of the caller
A function's return leaves the function. A macro's return expands inside the caller, so it leaves the caller:
macro_rules! some_or_zero {
($e:expr) => {
match $e {
Some(item) => item,
None => return 0,
}
};
}
fn first_plus_one(values: &[i32]) -> i32 {
let first = some_or_zero!(values.first());
*first + 1
}
fn main() {
println!("{}", first_plus_one(&[4, 5]));
println!("{}", first_plus_one(&[]));
}This prints 5 and then 0. Nothing in first_plus_one's body shows the early return, so use this power sparingly. The standard ? operator and return-style macros such as try! (now replaced by ?) show the same idea.
Macros can generate items
A function body can only contain statements. A macro can expand to a whole struct, trait implementation, or function at module level. This is the main reason crates use macros to remove repetitive boilerplate, for example to implement the same trait for a dozen integer types. Chapter "Generating structs, functions, and impls" covers this.
When a macro is the wrong choice
A function is easier to read, easier to debug, and gives better error messages. Prefer a function unless you need something it cannot do. Reach for a macro when you need one of these:
- A variable number of arguments, or arguments of different types in one call.
- Code at the item level, such as a struct or impl, generated from a short description.
- Control over how and whether an argument is evaluated, or a custom syntax such as
key => value. - A shortcut that must expand inline in the caller, for instance to use
returnor to declare a variable with a name the caller picks.
If a generic function with trait bounds does the job, use that.
Common mistakes for newcomers
- Treating a macro call like a function call. The arguments are not values. If the same argument expression appears twice in the output, it runs twice.
- Forgetting that a macro must be defined before use. A
macro_rules!definition is only visible after its position in the source file. Placing it below the call site producescannot find macro. The scoping chapter covers this and#[macro_export]. - Expecting
no rules expected the tokento point at the macro body. It points at the invocation and means that no rule matched what you wrote. Compare your call with the matchers, one rule at a time. - Using a macro where inference would work. Macros that avoid a type declaration still produce code that must type-check, and the error appears at the expansion.
What comes next
The next chapter defines a macro from scratch and walks through the anatomy of a macro_rules! definition: the name, the rules, and the matcher/transcriber split. The remaining chapters build on that structure.
Exercise
Given macro_rules! double_macro { ($e:expr) => { $e + $e }; } and a closure next that increments a counter and returns it, starting from 0, what does double_macro!(next()) evaluate to? What would a function fn double_fn(x: i32) -> i32 { x + x } return for double_fn(next()) on a fresh counter? Explain the difference.
Show answer
The macro expands to next() + next(), so the closure runs twice and the result is 1 + 2 = 3. The function receives the single value 1 produced by one call to next(), so it returns 1 + 1 = 2. A macro pastes the argument expression at each $e, while a function evaluates its argument once before the body runs.
Exercise
Name two things the standard println! macro does that a normal Rust function cannot, and say which stage of compilation makes them possible.
Show answer
It accepts any number of arguments of different types, and it checks the format string against the arguments at compile time. Both are possible because macro expansion runs after parsing and before type checking, so the macro sees the source tokens, including the format string literal, and generates code specific to each call.
Exercise
You need a helper that takes a &str and returns its length. Should you write a function or a macro? Give the reason.
Show answer
Write a function. It takes one argument of a fixed type, needs no custom syntax, does not generate items, and does not need to alter the caller's control flow. A function gives clearer error messages and is easier to read and debug.