macro

Macro metavariables and expression evaluation

A metavariable captures syntax, not a computed runtime value. Bind an expression to a local variable in the expansion if it should be evaluated only once. Expected stdout (not executed): '14 1\n' Common mistake: Writing $value + $value can repeat side effects.

Formal Syntax & Structure

rust syntaxrust
$value:expr => $value

Working Example

Example Snippetrust
macro_rules! doubled { ($value:expr) => {{ let n = $value; n + n }}; }fn main() {    let mut calls = 0;    let total = doubled!({ calls += 1; 7 });    println!("{total} {calls}");}
Rust Reference