Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Macro fragment specifiers

Reference for Rust macro fragment specifiers: expr, ident, ty, tt, pat, stmt, block, item, path, literal, lifetime, vis and meta, with matching rules.

In a macro_rules! pattern, $name:kind captures a piece of syntax and gives it a name. The fragment specifier (kind) says what grammar the captured tokens must follow. Choosing the right one decides what your macro accepts and what it can do with the capture.

Each captured fragment is parsed as a unit. An expr stays one expression no matter what operators it contains, so $a * $a with 1 + 2 multiplies (1 + 2) by itself, not 1 + 2 * 1 + 2.

Rust
macro_rules! show_type {
    ($t:ty) => { std::any::type_name::<$t>() };
}

Try it

Rust ident, ty, expr and literal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust pat, block, tt and vis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
$name:specifier
Specifier Matches
expr An expression: 1 + 2, foo(x), if a { b } else { c }.
ident An identifier or keyword-like name (not _), including raw identifiers.
ty A type: Vec<u8>, &'a str, fn(i32) -> i32.
pat A pattern, including `
pat_param A pattern without top-level `
stmt A statement without its trailing semicolon.
block A { ... } block.
item An item: function, struct, impl, use, and so on.
path A path such as std::collections::HashMap or Self::new.
literal A literal, possibly with a leading -.
lifetime A lifetime like 'a.
vis A visibility, possibly empty: pub, pub(crate), or nothing.
meta The inside of an attribute: derive(Debug), cfg(test).
tt A single token tree: one token, or a bracketed group with everything inside.

Usage notes

  • tt is the most flexible and lets you parse things by hand, with the cost of writing the parsing yourself.
  • What may follow a fragment is restricted. After expr and stmt only =>, , or ; may follow; after ty and path a small set including {, [, =>, ,, >, =, :, ;, |, as and where. The compiler tells you when a pattern breaks these rules.
  • An expr capture cannot be matched again by a literal-token rule in a nested macro call; it stays opaque. Pass tt if you need to re-inspect tokens.
  • ident vs expr. An identifier is also an expression; put the more specific rule first.
  • vis can match nothing, so it does not require pub.
  • Edition notes. In edition 2021 and later pat accepts top-level |; edition 2024 adds expr_2021 for the older expression grammar (const blocks and _ are expr only from 2024).