liveBook · Manning

Expression

As explained in Write Powerful Rust Macros

A Rust expression is a syntactic construct that evaluates to a value.

In a declarative macro matcher, expr matches one Rust expression and binds it to a macro variable such as $x. The dollar sign distinguishes the metavariable from a literal token. section 2.1.4

Use expression matchers to accept computed values while keeping the macro pattern more specific than tt:

  • Match $x:expr, push the captured value into a vector, and return the vector. section 2.1.4
  • Prefer expr when the macro expects an expression; reserve the broader tt matcher for cases that genuinely require almost any token sequence. section 2.1.4
  • Wrap multiple statements and the final value in braces when the macro must expand to one expression usable in a let binding. section 2.2.2

Capturing one expression

A matcher such as {$x:expr} can expand into a block that creates a vector, pushes $x, and returns v. Calling it with 1 produces a vector containing 1; the block remains a single expression. section 2.1.4 section 2.2.2

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

Inspect the matcher and transcriber that capture an expression, perform statements inside a block, and return the resulting vector. section 2.1.4

How Write Powerful Rust Macros covers it

How deep it goes
Explains expression capture, metavariable syntax, block grouping, and the trade-off between expr precision and tt breadth.
Examples
Demonstrates expression capture through vector-building macros and greeting macros that expand to function calls or braced blocks.
What it assumes
Assumes Rust macro matcher syntax while teaching expression metavariables and block expressions through concrete expansions.
What you can do after
Apply expression matchers to accept computed macro inputs and return multi-statement expansions as single expressions.
How it connects
Connects expressions with declarative macros, metavariables, fragment specifiers, token trees, and macro expansion.

Also explained in

Compare how 11 books explain expression →

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.