Macros
A macro in Rust is code that writes code at compile time. The exclamation mark in println!, vec! and format! marks a macro call, and the #[derive(Debug)] attribute above a struct is a macro call too, just of a different kind. The compiler expands a macro into ordinary code before type checking, and from then on that code is checked as strictly as code written by hand.
The key difference from the C preprocessor: a Rust macro works not with text but with tokens and syntax trees. That is why square!(2 + 3) gives 25 rather than 11, and why a variable declared inside a macro does not collide with a variable of the calling code.
There are two kinds of macros. Declarative ones are written with macro_rules! — pattern matching on tokens: "see a call like this — substitute this code". Procedural ones are Rust functions in a separate crate that take a token stream and return a new one. They come in three flavours: function-like, attribute and derive. Derive is the most common — #[derive(Clone)] from the standard library and #[derive(Serialize)] from serde.
You need a macro when a function cannot do the job: a variable number of arguments, generating declarations — functions, impl blocks — checks at compile time, walking a struct's fields. The price is code that is harder to read, worse error messages and slower builds. So you try a function or a generic first. The topic builds on Deriving Traits and walks through the material layer by layer — from macro_rules! to your own derive.
Topic map
- Declarative Macros —
(pattern) => { expansion }rules; theexpr,ident,ty,ttfragments;$(…),*repetitions and a trailing comma; recursion; hygiene of local variables, E0425; definition order,#[macro_export]and$crate. - Procedural Macros — function-like, attribute and derive; a separate crate with
proc-macro = truethat exports only macros;TokenStreamin and out;synandquote;compile_error!instead of a panic;cargo expand. - Derive Macros — what the built-in
#[derive(Clone)]generates and where the extraT: Clonebound comes from; your own derive withsynandquote; a trait and a macro of the same name in different crates; helper attributes; derive only adds code.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Expecting text substitution from macro_rules!, as from #define | $x:expr is substituted as a whole expression: square!(2 + 3) gives 25; you also cannot glue a new identifier out of pieces |
| Referring to a variable declared inside the macro from the passed expression | Hygiene: error[E0425]: cannot find value `a` in this scope — pass the name as a $name:ident argument |
Calling a macro_rules! macro above its definition in the file | error: cannot find macro `hello` in this scope — a macro is visible only after its definition |
| Declaring a trait next to a procedural macro in its crate | error: `proc-macro` crate types currently cannot export any items other than functions tagged with `#[proc_macro]`, `#[proc_macro_derive]`, or `#[proc_macro_attribute]` |
Reporting an error in a procedural macro with panic! | error: proc macro panicked points at the whole call; compile_error! or syn::Error point at the right token |
Deriving #[derive(Clone)] for a generic wrapper around Rc<T> | Derive requires T: Clone; for a T without Clone you get E0599 and need a manual impl<T> Clone |
| Writing a macro where a function or a generic is enough | Worse error messages and IDE hints, longer builds, harder to read |
Why it matters in interviews
Macros are a middle-level topic: the candidate is not expected to write complex procedural macros, but to understand that a macro expands at compile time, how the two kinds differ and when a macro is justified. Almost always they ask why println! is a macro and ask you to write a small macro_rules!.
What interviewers usually check:
- Why
println!andvec!are macros: a variable number of arguments and a format string checked at compile time. - How
macro_rules!differs from a procedural macro, and when a macro beats a function. - How to write a macro like
vec!with a$(…),*repetition, and what theexpr,ident,ttfragments are. - Which kinds of procedural macros exist and why they need a separate crate.
- What
#[derive]generates and whyDisplaycannot be derived. - Why Rust macros are safer than C macros: tokens instead of text, and hygiene.