Macros & Metaprogramming · 19 min · free lesson

macro_rules!

macro_rules! matches syntax patterns and expands to code.

Core idea

Macros work on tokens before type checking, which is why they can vary in arity.

A fictional macro invocation matches two expression fragments and expands into a Rust expression at compile time.
A declarative macro transforms matched syntax before the expanded program is type-checked.

Understand it

A declarative macro takes token trees, not values, so it can accept a variable number of arguments and shapes a function cannot. Fragment specifiers such as expr and ident say what each capture must be, and the expansion is type-checked afterwards like any other code.

A macro_rules! definition contains arms. Each arm has a pattern that matches input syntax and a transcriber that emits output syntax. The compiler tries arms in order. In maximum!, the one-expression arm ends recursion; the repeated arm captures one expression and a nonempty comma-separated rest. That is a compile-time transformation. Values are evaluated only when the expanded Rust code runs, and the expansion is type-checked in the caller's context. A macro can accept shapes that an ordinary function signature cannot, but this flexibility raises the cost of reading errors and maintaining the API.

Trace maximum!(3, 9, 2) on paper: the repeated arm reduces the tail, then compares the first expression with that result. Ask whether an argument with side effects is evaluated once. The temporaries first and rest keep each argument to one evaluation, and every arm deserves the same review. Use a function when types and arity are fixed; use a macro when syntax transformation or variable arity is essential. Keep exported macros small, document accepted forms, and test both successful expansions and expected compile failures. When an error appears far inside generated code, inspect the expansion and simplify the invocation until the mismatched pattern is clear.

Macro expansions can evaluate captured expressions more than once if the transcriber repeats them. For an expression with side effects, that changes program behavior. Use temporary bindings and inspect each arm. Also avoid returning a fragment with unexpected precedence; wrap a generated expression in a block or parentheses where its surrounding syntax could change how it is parsed.

Read the code

macro_rules! maximum {
    ($first:expr) => { $first };
    ($first:expr, $($rest:expr),+) => {{
        let first = $first;
        let rest = maximum!($($rest),+);
        if first > rest { first } else { rest }
    }};
}

println!("{}", maximum!(3, 9, 2, 7));

Two arms, any number of arguments, all checked after expansion.

Practice starter

macro_rules! square {
    ($value:???) => { $value * $value };
}

println!("{}", square!(3 + 1));

Practise this code in Playground ↗

Try it

Write a macro that accepts a variable number of expressions.

What success looks like: It expands correctly for one, two, and many arguments.

Check your understanding

Which fragment specifier replaces ??? so that $value accepts any expression?

Reveal the answer
  1. ident
  2. expr
  3. tt

expr captures a whole expression and keeps its grouping, so square!(3 + 1) is 16.

Go deeper

Common misconception: “A captured expr is evaluated once, like a function argument.”

Macros work on tokens before type checking, so a captured expr is pasted wherever the transcriber repeats it. Bind it once with let if it may have side effects.

  1. Match an arm: maximum!(3, 9, 2, 7) has several arguments, so the first arm fails and the second binds $first to 3 and $rest to 9, 2, 7.
  2. Expand the tail: The second arm calls maximum! again with one fewer argument, until only 7 remains and the first arm matches.
  3. Compare once: Each level binds first and rest with let, so every argument is evaluated once and the result printed is 9.

Transfer challenge: Call the practice's square! with a block that prints when evaluated, and count the prints. Then bind $value with let so there is only one.

Connections

  • Procedural Macros: Derive, attribute, and function macros
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: macro_rules! (courseId "systems", lessonId "declarative-macros")
Link: https://crabrix.com/learn/systems/declarative-macros/
Goal: Macros work on tokens before type checking, which is why they can vary in arity.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/declarative-macros) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.