Macros
`macro_rules!` and hygiene, procedural and derive macros, and when a macro is the right tool.
6 questions
JuniorTheoryCommonWhy is println! a macro and not an ordinary function in Rust?
Why is println! a macro and not an ordinary function in Rust?
A Rust function has a fixed list of typed parameters, while println! takes any number of arguments of any printable type and checks the format string against them at compile time. A macro can also generate items such as functions.
Common mistakes
- ✗Explaining
println!as a macro just for brevity, missing the variable argument count and the compile-time format check - ✗Expecting a mismatch between
{}placeholders and arguments to fail at run time, though it is a compile error - ✗Thinking a macro pastes text like
#define, though it works on tokens and parsed expressions
Follow-up questions
- →Why does
square!(2 + 3)expanding to$x * $xgive 25 rather than 11? - →When would you still choose a generic function over a macro, even if both work?
MiddleTheoryCommonDeclarative vs procedural macros: how do they differ, and when write one?
Declarative vs procedural macros: how do they differ, and when write one?
macro_rules! matches call tokens against patterns and substitutes a template; a procedural macro is a Rust function in a proc-macro crate that the compiler runs on a TokenStream. Use either only when a function or generic cannot.
Common mistakes
- ✗Thinking a procedural macro runs when the program runs, though the compiler executes it during the build
- ✗Writing a macro to save a few lines where a function or a generic would do, and paying with worse errors and slower builds
- ✗Expecting a procedural macro to live in the same crate as the code that calls it
Follow-up questions
- →Why does a procedural macro slow the build more than a
macro_rules!macro? - →What does the Cargo subcommand
cargo expandshow, and when do you need it?
JuniorTheoryOccasionalHow do you define a one-argument macro_rules! macro and where can you call it?
How do you define a one-argument macro_rules! macro and where can you call it?
Write macro_rules! name { ($x:expr) => { … }; } — a pattern for the call and the code it expands into — and call it as name!(value). It is visible only below its definition in the file; other crates need #[macro_export].
Common mistakes
- ✗Calling the macro above its definition and getting
cannot find macro … in this scope - ✗Expecting
$x:exprto be pasted as text, thoughsquare!(2 + 3)with$x * $xgives 25 - ✗Forgetting
#[macro_export]when another crate must call the macro
Follow-up questions
- →Why does an expansion with several
letstatements need double braces{{ … }}? - →Why should an exported macro call its helper functions through
$crate::?
MiddleCodeOccasionalWrite a hashmap! macro that builds a HashMap from key => value pairs
Write a hashmap! macro that builds a HashMap from key => value pairs
Two rules: () => { HashMap::new() } and ($($k:expr => $v:expr),+ $(,)?), whose block makes a map, repeats map.insert($k, $v); with $( … )+ and returns it. expr takes a whole expression; $(,)? allows a trailing comma.
Common mistakes
- ✗Using single braces, so an expansion that starts with
letfails in expression position withexpected expression, found `let` statement - ✗Leaving out
$(,)?, so a trailing comma after the last pair ends inunexpected end of macro invocation - ✗Using
$koutside its$( … )group, which rustc rejects as still repeating at this depth
Follow-up questions
- →How would you make
hashmap!preallocate capacity by counting the pairs at compile time? - →Why does rustc allow only
=>,,or;right after anexprfragment?
MiddleTheoryOccasionalWhat kinds of procedural macros exist, and why do they need a separate crate?
What kinds of procedural macros exist, and why do they need a separate crate?
Function-like #[proc_macro], attribute #[proc_macro_attribute], which may rewrite its item, and derive, which only adds code: #[derive(Serialize)] adds impl Serialize. The crate is loaded into rustc, so it exports only macros.
Common mistakes
- ✗Declaring the trait in the macro crate, which may export only macros
- ✗Thinking a derive can change the struct it is attached to, though only an attribute macro can rewrite an item
- ✗Believing
#[derive(Serialize)]works through run-time reflection, though it generates animplat compile time
Follow-up questions
- →Why does the serialization crate
serdeship its derive macros in a separateserde_derive? - →How should a procedural macro report a user error instead of panicking?
SeniorTheoryOccasionalWhat does macro hygiene hide in macro_rules!, and where does it not apply?
What does macro hygiene hide in macro_rules!, and where does it not apply?
Locals and labels a macro declares get its own syntax context: its let x does not clash with the caller's x, and passed code cannot see it. Items, paths and $name:ident names resolve at the call site, hence $crate::.
Common mistakes
- ✗Expecting an argument expression to see a variable the macro declares, which fails with E0425
- ✗Assuming items a macro generates are hidden as well, though a generated
fnis visible to the caller - ✗Writing bare paths in an exported macro, which then resolve at the call site and break in other crates
Follow-up questions
- →How do procedural macros choose hygiene with
Span::call_siteandSpan::mixed_site? - →How do you let the caller name a variable that the macro declares?