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.
macro_rules! show_type { ($t:ty) => { std::any::type_name::<$t>() }; }
Try it
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.
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
$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
ttis 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
exprandstmtonly=>,,or;may follow; aftertyandpatha small set including{,[,=>,,,>,=,:,;,|,asandwhere. The compiler tells you when a pattern breaks these rules. - An
exprcapture cannot be matched again by a literal-token rule in a nested macro call; it stays opaque. Passttif you need to re-inspect tokens. identvsexpr. An identifier is also an expression; put the more specific rule first.viscan match nothing, so it does not requirepub.- Edition notes. In edition 2021 and later
pataccepts top-level|; edition 2024 addsexpr_2021for the older expression grammar (constblocks and_areexpronly from 2024).