Sub topic 1
Why macros exist and how they differ from functions
Prerequisites
This chapter assumes you can read basic Rust: functions, let bindings, structs, and the println! macro. You should know what an expression and a type are, and be able to build and run a project with Cargo. You do not need to have written a macro before.
What a macro is
A declarative macro is a named set of pattern-matching rules. At compile time, the compiler matches the code you pass to the macro against those patterns. It then replaces the macro call with new code built from the matching rule. This replacement is called expansion. It happens before type checking, so the expanded code is checked as if you had typed it yourself.
You have already used macros. println!, vec!, and assert_eq! all end in !, which marks a macro call. Rust defines your own declarative macros with macro_rules!.
Where functions fall short
A function takes values of fixed types, in a fixed number. That is a limit in several common cases.
- Variable arguments. A function cannot take a different number of arguments per call.
println!("{} {}", a, b)andprintln!("{}", a)are both valid becauseprintln!is a macro. - Code that is not a value. A function receives evaluated values. It cannot receive a type name, a field name, or a block of statements as an argument.
- Generating items. A function cannot define a new struct,
implblock, or function. A macro can expand to items. - Repeated boilerplate. Writing the same shape of code for ten types is tedious. A macro can write it for you.
How macros differ from functions
| Property | Function | `macro_rules!` macro |
|---|---|---|
| When it runs | At run time | At compile time |
| Input | Typed, evaluated values | Unevaluated token sequences |
| Argument count | Fixed | Can vary through repetition |
| Output | A value | Code that replaces the call |
| Errors | Reported against the function signature | Reported against the expanded code |
The key difference is in the middle row. A function sees the value 5. A macro sees the tokens that make up 2 + 3, before anything is computed.
A first comparison
Here is a function and a macro that both square a number.
fn square_fn(x: i32) -> i32 {
x * x
}
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square_fn(2 + 3));
println!("{}", square!(2 + 3));
}Both lines print 25. The function evaluates 2 + 3 to 5 first, then multiplies. The macro receives 2 + 3 as an expression and expands to a product of two complete expressions. Because the argument is matched as a single expression, Rust keeps it grouped, so you do not get 2 + 3 * 2 + 3. A later chapter covers the expr fragment specifier in detail.
The function has one advantage here. It works only on i32, but the type is checked at the signature, and the error messages are clear. The macro works on any type that supports *, but a mistake shows up as an error in the expanded code.
Costs of macros
Macros are not free. Keep these in mind before reaching for one.
- Errors can be harder to read, because they point into expanded code.
- Each call site is expanded separately, which can increase compile time and code size.
- A macro with several rules is harder to read and maintain than a function.
- A macro can evaluate an argument more than once.
square!writes$xtwice, sosquare!(next())would callnext()twice.
A good rule is to use a function when one will do. Choose a macro when you need variable arguments, code-shaped input, or generated items.
Exercise
You want a helper that accepts any number of arguments, such as max_of!(1, 5, 3) and max_of!(4, 2). Why can a plain function not do this, and what does a macro do differently?
Show answer
A function has a fixed parameter list, so every call must pass the same number of arguments. A macro receives the call's tokens unevaluated and can use repetition patterns to match any number of arguments, then expand to code built from them at compile time.