Sub topic 1
Declarative macros versus procedural macros
Rust has two macro systems. This chapter explains how they differ and how to choose between them. Later chapters build each kind of procedural macro.
Prerequisites
This chapter assumes you can read Rust structs, enums, traits, and generics. You should know how to add a dependency in Cargo. You should also have used a derive attribute such as #[derive(Debug)]. You do not need to have written a macro_rules! macro.
What a macro does
A macro is code that writes code. The compiler runs it during compilation and replaces the macro call with the code it produces. The result must be valid Rust, and the compiler checks it like any other code.
Rust has two families of macros:
- Declarative macros are defined with
macro_rules!. They match patterns in the call and substitute pieces into a template. - Procedural macros are Rust functions. They receive the call's tokens, run ordinary Rust code, and return new tokens.
A token is the smallest unit of source code the compiler recognizes, such as an identifier, a literal, or a punctuation mark.
Declarative macros
A declarative macro works like a match expression over code. Each arm has a pattern and a template.
macro_rules! square {
($x:expr) => {
$x * $x
};
}
fn main() {
println!("{}", square!(4));
}This prints 16. The pattern $x:expr matches any expression. The template repeats it twice. Declarative macros need no extra crate and can live in the same crate as the code that uses them. Their limit is that they can only rearrange the pieces they match. They cannot inspect a struct's field names and build code from them.
Procedural macros
A procedural macro is a function that takes a TokenStream and returns a TokenStream. Because it is ordinary Rust, it can loop, branch, and build strings. The three kinds differ in how you call them and what they receive.
| Kind | Written as | Input | Output |
|---|---|---|---|
| Function-like | `my_macro!(...)` | The tokens in the parentheses | Replaces the call |
| Derive | `#[derive(MyTrait)]` | The struct, enum, or union | Added after the type |
| Attribute | `#[my_attr(...)]` | The arguments and the item | Replaces the item |
A derive macro cannot change the type it annotates. It can only add new items, such as a trait implementation. An attribute macro can rewrite or replace the whole item.
Procedural macros must live in their own crate, marked as a proc-macro crate. The next chapter shows the setup. The requirement exists because the compiler must build and load the macro before it can compile the code that uses it.
Choosing between them
Start with macro_rules! when you can. It is simpler and adds no build cost. Move to a procedural macro when you need one of these:
- Read a type's fields, variants, or generics and generate code from them.
- Parse custom syntax that patterns cannot describe.
- Produce precise compiler errors that point at the user's code.
- Rewrite a function or other item.
Procedural macros cost more. They need a separate crate, extra dependencies, and longer compile times.
Common mistakes
- Reaching for a procedural macro when a short
macro_rules!would do. - Expecting a derive macro to modify the struct. It can only add items.
- Putting a procedural macro in a normal library crate. It must be in a crate with
proc-macro = true.
Exercise
You want #[derive(FieldNames)] to return the names of a struct's fields as strings. Why can't macro_rules! do this cleanly, and which procedural macro kind fits?
Show answer
A macro_rules! macro only matches patterns in the tokens it is called with, and a derive attribute hands it no usable view of the struct's fields in a way it can match. A derive macro receives the whole type definition, so it can read the field names in ordinary Rust code and generate an impl. The derive kind fits.
Exercise
A macro must wrap an existing function so it prints a message before running. Which kind do you use, and why not a derive macro?
Show answer
Use an attribute macro. It receives the function and returns a replacement. A derive macro only adds new items next to a type and cannot change an existing function.