Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 132 ยท Modules, Packages and Macros

Declarative Macros (macro_rules!)

Learn Rust declarative macros with macro_rules!: fragments, repetitions, recursion, hygiene, and how to build vec!-like and hashmap! macros step by step.

You have been calling macros since your first program: println!, vec!, format!, assert_eq!. The exclamation mark tells you that this is not a normal function call. A macro is code that writes code. Before the compiler checks types and borrows, it expands every macro call into ordinary Rust, and only then looks at the result.

The kind you write yourself most often is the declarative macro, defined with macro_rules!. It works like a match expression, but instead of matching values it matches pieces of source code and produces new source code. This lesson shows how to read and write them: fragments, repetitions, recursion, hygiene, and a few real-world patterns. The next lesson, Procedural and Derive Macros, covers the other family.

Why macros exist

A function has a fixed number of parameters, each with a fixed type. println!("{} {}", a, b) takes any number of arguments of any displayable type, checks the format string at compile time, and does not even evaluate arguments you never use. No ordinary function can do that. Macros fill the gaps functions cannot:

  • Variable argument counts (vec![1, 2, 3], println!).
  • Compile-time work such as checking a format string or generating a match arm per item.
  • Removing repetition when you would otherwise copy and paste the same impl block for ten types.
  • New syntax shapes that read like a small language of your own (hashmap! { "a" => 1 }).

The price is that macros are harder to read, harder to debug, and give worse error messages than functions. The rule of thumb: reach for a function or a generic first, and a macro only when those cannot do the job.

Your first macro

A macro has a name and one or more rules. Each rule is (pattern) => { expansion };. The compiler tries the rules from top to bottom and uses the first pattern that matches.

Rust A macro with one rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read the pattern $x:expr as "match any expression and call it $x". The part after => is a template: wherever $x appears it is replaced with the matched code.

Notice that square!(2 + 3) prints 25, not 11. If macros were plain text substitution as in C, 2 + 3 * 2 + 3 would give 11. Rust macros work on the syntax tree: an expr fragment stays one single expression node, so it behaves as if wrapped in parentheses. That one design choice removes a whole class of C preprocessor bugs.

Macros must be defined before they are used in the file (textual order matters for macro_rules!), unlike functions.

Fragment specifiers

The text after the colon in $name:kind is the fragment specifier. It says what kind of syntax the variable matches.

Specifier Matches Example
expr an expression 1 + 2, foo(x)
ident an identifier or keyword-like name counter, Point
ty a type Vec<i32>, &str
pat a pattern Some(x), 1..=5
stmt a statement without trailing semicolon let x = 5
block a { ... } block { a + b }
item an item (fn, struct, impl ...) fn f() {}
path a path std::fmt::Debug
literal a literal 42, "hi", true
lifetime a lifetime 'a
vis a visibility (may be empty) pub, pub(crate)
meta the inside of an attribute derive(Debug)
tt a single token tree +, foo, (a, b), { ... }

tt is the escape hatch. A token tree is either one token or a whole bracketed group (...), [...], {...}. When no other specifier fits, tt lets you accept anything and decide later.

Rust ident and ty: generating functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Because the macro is called at item level (outside any function), its expansion is two ordinary function definitions. $name:ident is what makes it possible to invent a function name from the call site: a plain function could never define other functions.

Repetitions

The real power starts with repetition. The syntax is $( ... ) separator? repeat where repeat is * (zero or more), + (one or more) or ? (zero or one). Inside the template you repeat the same group with $( ... )* using the variables captured under the same repetition.

Here is a simplified vec!:

Rust A tiny my_vec! macro

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Things to notice:

  • Two rules: the empty call, and one-or-more comma-separated expressions.
  • $( $item:expr ),+ means "an expr, then a comma and another expr, repeated one or more times".
  • $(,)? allows an optional trailing comma, so my_vec![1, 2, 3,] works as it does for the real vec!.
  • The expansion uses double braces {{ ... }}. The outer braces are the macro syntax; the inner ones create a block, so the let mut v statement and the final v form a single expression. Without the inner block the macro would try to expand into statements in expression position and fail.
  • $( v.push($item); )+ repeats once per captured item.

Nested repetition and key-value macros

You can capture several variables in one repetition. A hashmap! macro is a classic example. We use BTreeMap here so the output order is stable:

Rust A map! macro with key and value pairs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Macros can be invoked with (), [] or {}; they are interchangeable for the parser. The convention is () or [] for expression-like macros, and {} for block-like ones such as this map! { ... }.

Recursion

A rule's expansion may call the macro again with a shorter input. This "peel one item and recurse" pattern is how you process lists that need different handling per element, or how you compute something at compile time.

Rust Recursive macros: max and count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

max_of!(3, 9, 4) expands to a comparison of 3 against max_of!(9, 4), which expands again, and so on until one expression is left. count! uses tt so that it can swallow any tokens; the result 1 + (1 + (1 + (1 + 0))) is a constant expression, so it works in a const.

There is a limit: the compiler stops at a recursion limit (128 levels by default), and each level costs compile time. Counting 500 tokens this way fails. You can raise it with #![recursion_limit = "256"] at the top of the crate, but a better design is usually a repetition inside one rule instead of recursion.

The rule order matters here. In max_of!, the single-expression rule is listed first. If you listed the recursive rule first, max_of!(5) would not match it (it needs a comma and + rest), so it would fall through. But more subtly, a greedy rule placed first can swallow input that a more specific rule below was meant to handle. Put the most specific rules first.

Hygiene

C macros paste text, so a variable named a inside a macro can collide with the caller's a. Rust macros are hygienic for local variables: names introduced inside the macro live in their own syntactic context and cannot clash with, or capture, names at the call site.

Rust Hygiene keeps local names apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The macro declares its own tmp, yet double_it!(tmp + 1) still uses the caller's tmp and prints 22. Hygiene covers local variables and labels only. It does not cover items: a function, struct or type defined by a macro is visible to the caller, and a macro that mentions Vec or HashMap resolves them at the call site, so inside a macro use full paths such as ::std::vec::Vec or $crate::helper() when you write macros for other people. $crate always refers to the crate that defined the macro.

If you want the caller to supply a name, accept it as an ident parameter, as make_adder! did above.

Common compile errors

A pattern that does not match any rule is an error that names the macro and shows the unexpected token. Let us trigger one on purpose.

Rust No rule matches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc reports error: unexpected end of macro invocation and points at the call with the label missing tokens in macro arguments, plus a note saying it was trying to match a comma, which points into the macro definition. Read it as "none of the rules accepted this input". The fix is to give the macro the tokens it expects (pair!(1, 2)) or to add a rule that accepts one argument.

Another common mistake is using a fragment that is too greedy. After an expr fragment, Rust only allows =>, , or ; as the next token, so ($a:expr $b:expr) is rejected when the macro is defined. These follow-set restrictions exist so that later versions of the language can extend expression syntax without breaking your macros. If you need free-form syntax, use tt.

A practical example: implementing a trait for many types

The most common reason to write a macro_rules! in real code is removing repetitive impls:

Rust One macro, many impls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard library does exactly this to implement traits for all integer types. Today const generics and blanket impls replace some of those uses, but for a closed list of unrelated primitive types a macro is still the clearest tool.

Debugging macros

Rust gives you a few helpers:

  • cargo expand (a third-party Cargo subcommand, read-only here) prints your crate after macro expansion.
  • rustc -Zunpretty=expanded does the same on nightly. Neither is available in our in-browser editor.
  • trace_macros! and log_syntax! are unstable.
  • The simplest trick: expand by hand. Write down the call, apply the first matching rule, substitute, and repeat. Most bugs are visible after two steps.
Terminal
# On your own machine (not in the browser editor)
cargo install cargo-expand
cargo expand            # whole crate
cargo expand my_module  # only one module

Also remember that a macro call that expands to a compile error reports the error at the call site, with a note in this macro invocation. Keep macros small, give them tests (an ordinary #[test] calling the macro), and document the accepted syntax in the doc comment above the macro.

Exporting a macro to other crates uses #[macro_export], which places it at the crate root (mycrate::my_macro!). Inside one crate, textual order and #[macro_use] on modules also matter. In the 2018+ editions you can bring a macro into scope like any item with use once it is exported or defined with the pub(crate) use name; trick.

When to use and when to avoid

Use macro_rules! when:

  • you need a variable number of arguments or custom syntax,
  • you generate many similar items (impls, tests, enum variants with a lookup table),
  • you must run at compile time on syntax, not values.

Avoid it when:

  • a generic function or trait would work (they give better errors and IDE support),
  • the macro hides control flow such as an early return or ? that readers will not expect,
  • the invocation needs a long tutorial to understand. Surprising macros are technical debt.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a macro_rules! rule match against?

    Declarative macros are pattern matchers over source code. They run before type checking and produce new source code.
  2. 2. Why does square!(2 + 3) print 25 with ($x:expr) => { $x * $x }?

    Macro arguments are syntax trees, not text, so 2 + 3 is multiplied as a single unit, giving 5 * 5 = 25.
  3. 3. What does $( $item:expr ),+ $(,)? accept?

    ,+ means one or more repetitions separated by commas, and $(,)? is an optional single comma at the end.
  4. 4. What does hygiene guarantee?

    Hygiene separates the naming contexts for local variables and labels. Items such as functions and types defined by a macro are still visible to the caller.
  5. 5. Which fragment specifier would you use to let a macro define a new function name from the call site?

    ident matches an identifier, which you can then use as the name in fn $name() { ... }.

Summary

  • A macro_rules! macro is a list of (pattern) => { template }; rules tried in order; the first match wins, so put specific rules first.
  • Fragment specifiers (expr, ident, ty, tt, ...) say what kind of syntax a $variable captures; tt accepts any single token tree.
  • Repetitions $( ... ) sep rep with *, + or ? accept lists and generate repeated code; $(,)? allows a trailing comma.
  • Use {{ ... }} when the expansion needs statements and a final value.
  • Recursion handles list processing but is limited by the recursion limit; prefer repetition when possible.
  • Hygiene protects local variables; use $crate and full paths for items in exported macros.
  • Prefer functions and generics; use macros for variable arity, custom syntax and removing impl boilerplate.

Next: Procedural and Derive Macros