liveBook · Manning

Declarative macro

As explained in Learn Rust in a Month of Lunches

macro_rules! is Rust syntax for defining declarative macros by matching token sequences and expanding them into source code.

A declarative macro uses macro_rules! to match token sequences and expand them into Rust source code. It resembles match syntax, but it parses tokens first and lets the compiler check the generated code afterward. section 22.2

A macro rule can:

  • Match exact tokens such as () or 6. section 22.2
  • Capture structured input with fragment specifiers such as expr, stmt, ident, and tt. section 22.2
  • Repeat captured token trees with separators and repetition operators. section 22.2
  • Generate functions or other source code from captured names and tokens. section 22.2

A minimal expansion

macro_rules! give_six { () => { 6 }; } lets give_six!() expand to 6. A separate rule can print a message for (), while an unmatched input such as 66 produces “no rules expected the token.” section 22.2

macro_rules! give_six {
    () => {
        6
    };
}
 
fn main() {
    let six = give_six!();
    println!("{}", six);
}

Use the minimal give_six! listing to see a complete declarative macro and its call. section 22.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains exact matching, fragment capture, repetition, diagnostics, and generated functions, but stops short of deeper macro internals.
Examples
Uses give_six!, six_or_print!, expression and statement captures, token-tree printing, repetitions, and generated functions.
What you can do after
Build declarative macros that match literals or fragments, repeat inputs, substitute captures, and interpret compiler feedback.
How it connects
Connects token parsing with match statements, expressions, statements, token trees, repetition, and source generation.

Also explained in

Compare how 3 books explain declarative macro →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.