Sub topic 2
Your first macro_rules! macro
This chapter assumes you can write Rust functions, let bindings, and structs, and that you can build and run a project with Cargo. You should also know that println! is a macro. Here you define a macro, invoke it, and see what the compiler does with it.
The shape of a definition
A declarative macro is defined with macro_rules!, followed by the macro's name and a body in braces. The body holds one or more rules. Each rule has a matcher on the left and a transcriber on the right, joined by =>.
macro_rules! say_hello {
() => {
println!("Hello from a macro");
};
}
fn main() {
say_hello!();
}The matcher () accepts an invocation with no arguments. The transcriber is the code that replaces the invocation. The ! after the name tells the compiler this is a macro call, not a function call.
The delimiters around a rule can be (), [], or {}, and the compiler treats them the same way. Most code uses braces for the transcriber. Rules end with a semicolon, and the last one may omit it.
A macro with an argument
A matcher can capture part of the invocation into a variable. A variable starts with $, followed by a name, a colon, and a fragment specifier. The specifier says what kind of syntax to match. This macro uses expr, which matches any Rust expression.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(2 + 3));
}This prints 25. The argument 2 + 3 is parsed as one complete expression, so the expansion behaves like (2 + 3) * (2 + 3). It does not become 2 + 3 * 2 + 3, which would give 11. Later chapters cover fragment specifiers in detail. For now, remember that expr keeps the argument together as a unit.
What happens at compile time
Expansion happens before type checking. The compiler parses your code, finds each macro invocation, and tries the rules from top to bottom. The first matcher that fits is used. The captured pieces are substituted into its transcriber, and the result replaces the invocation.
If no rule matches, the compiler reports an error such as no rules expected the token. If a rule matches but the expanded code is invalid, the error comes from the expanded code. That is why type errors in macro output can point at the invocation site.
Common first errors
- Using a macro before defining it.
macro_rules!macros are visible only after their definition in the file. Put the definition above the code that calls it. - Forgetting the
!. Writingsquare(3)looks for a function calledsquare. - Using
$xwith no specifier in the matcher. A matcher variable needs:expr,:ident, or another fragment kind. - Mismatched invocation.
square!(1, 2)fails because the only matcher expects a single expression and nothing after it.
Why define one at all
You could write square as a function, and for numbers you probably should. A macro is worth it when a function cannot do the job. Examples are accepting a variable number of arguments, generating items such as structs, and creating bindings in the caller's scope. The next chapters build toward those cases.
Exercise
Write a macro called double that takes one expression and expands to that expression multiplied by 2. What does double!(1 + 2) print inside println!("{}", ...), and why is it not 5?
Show answer
The macro is macro_rules! double { ($x:expr) => { $x * 2 }; }. It prints 6. The expr fragment captures 1 + 2 as one expression, so the expansion is (1 + 2) * 2. It is not 1 + 2 * 2, which would give 5.