Rust Reference ยท Macros
Rust macro_rules! declarative macros
Reference for Rust macro_rules!: defining macros with pattern-matching rules, hygiene, scoping with macro_use and macro_export, recursion and debugging.
macro_rules! defines a declarative macro: a set of rules, each with a pattern that matches the tokens you pass and a template that is written out in their place. The compiler tries the rules from top to bottom and uses the first one that matches. Macros run before type checking, so they can create items, accept a variable number of arguments and write code that functions cannot.
A macro call is written with !. The expansion must be valid Rust in the place where the call appears (expression, statement, item or pattern).
macro_rules! square {
($x:expr) => { $x * $x };
}
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
macro_rules! name { (pattern) => { expansion }; (pattern) => { expansion }; // more rules }
| Part | Description |
|---|---|
pattern |
Tokens to match literally, plus $var:fragment captures and $(...) repetitions. |
expansion |
Tokens produced; $var inserts a capture. |
| delimiters | Rules are separated by ;. The outer and inner brackets may be (), [] or {}. |
See fragment specifiers for expr, ident, ty and the rest, and repetitions for $(...)*.
Usage notes
- Order matters. Put more specific rules first; a general rule like
($($t:tt)*)placed first swallows everything. - Hygiene. Local variables created inside a macro do not clash with the caller's names (shown above). Items such as functions and types are not hygienic.
- Scope. A macro is usable only after its definition in the file.
#[macro_use]on a module extends it past the module;#[macro_export]makes it available at the crate root for other crates. - Expression results. Wrap multi-statement expansions in
{ ... }or{{ ... }}so the macro works as an expression, and evaluate each$e:expronce into aletif you use it twice. - Recursion is allowed up to a limit (
#![recursion_limit], default 128). - Error messages point at the expansion, which can be confusing. Test macros with small inputs, and use
cargo expandon a full project to see the output. - When not to use. If a generic function or trait does the job, prefer it; macros are harder to read and debug.