liveBook · Manning

Expression fragment specifier

As explained in Learn Rust in a Month of Lunches

An expression fragment specifier matches a Rust expression as macro input.

An expression fragment specifier, written `$input:expr`, lets a `macro_rules!` macro accept a Rust expression and reuse it under the chosen argument name. The macro matches structured input rather than only literal tokens. section 22.2

Matching expressions

A macro using `$input:expr` can print `()`, `6`, or `vec![8, 9, 7, 10]`. The compiler checks whether the generated use is valid, such as whether a value supports `Debug`. Passing `let x = 9` fails because that input is a statement, not an expression; changing the matcher to `$input:stmt` accepts it. section 22.2

macro_rules! might_print {
    ($input:expr) => {
        println!("You gave me: {:?}", $input);
    }
}
 
fn main() {
    might_print!(());
    might_print!(6);
    might_print!(vec![8, 9, 7, 10]);
}

Compare several accepted expression inputs in a focused `macro_rules!` example. section 22.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains matcher syntax, accepted examples, generated-code checking, and the expression-versus-statement error, but not macro parsing internals.
Examples
Demonstrates unit values, integers, vectors, and an invalid `let` statement passed to an expression matcher.
What it assumes
Introduces macro arguments and token matching while assuming basic Rust syntax and familiarity with expressions and statements.
What you can do after
Build it from scratch by writing a `macro_rules!` matcher that accepts and reuses one Rust expression.
How it connects
Connects expression fragments with declarative macros, statements, compiler checking, and other fragment specifiers.

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.