liveBook · Manning

Macro parameter

As explained in Write Powerful Rust Macros

A macro variable is a named binding in a declarative macro that refers to syntax captured by a matcher.

A macro parameter is a named binding that captures syntax matched by a declarative macro. Write a dollar sign before the name: `$x:expr`. The dollar sign makes `x` a macro variable; `expr` restricts the match to one Rust expression. section 2.1.4

{$x:expr} => {
    {
        let mut v = Vec::new();
        v.push($x);
        v
    }
};

This matcher captures an expression in `$x` and reuses it in the transcriber to push that value into a vector. section 2.1.4

Fragment specifiers determine what a parameter accepts. Common targets include expressions, identifiers, literals, and types. Prefer the most concrete specifier that fits: `tt` accepts almost anything, but makes matchers broader, less predictable, and harder to manage. section 2.1.4

Capturing repeated expressions

A repetition such as `$[($x:expr),+]` captures one or more comma-separated expressions, then expands `$x` for each value in the generated code. section 2.1.4

How Write Powerful Rust Macros covers it

How deep it goes
Defines dollar-prefixed bindings and fragment specifiers, then compares precise matches with broad `tt` matching.
Examples
Demonstrates empty-vector expansion, expression capture, vector insertion, and repeated comma-separated expressions.
What it assumes
Assumes Rust macro syntax, while teaching the dollar-sign binding and fragment-specifier roles from the examples.
What you can do after
Build declarative macro arms that capture expressions and expand them into generated Rust code.
How it connects
Connects declarative macros with matchers, transcribers, fragment specifiers, expressions, and token trees.

Also explained in

Compare how 2 books explain macro parameter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.