A declarative macro uses macro_rules! to match token sequences and expand them into Rust source code. It resembles match syntax, but it parses tokens first and lets the compiler check the generated code afterward. section 22.2
A macro rule can:
- Match exact tokens such as () or 6. section 22.2
- Capture structured input with fragment specifiers such as expr, stmt, ident, and tt. section 22.2
- Repeat captured token trees with separators and repetition operators. section 22.2
- Generate functions or other source code from captured names and tokens. section 22.2
A minimal expansion
macro_rules! give_six { () => { 6 }; } lets give_six!() expand to 6. A separate rule can print a message for (), while an unmatched input such as 66 produces “no rules expected the token.” section 22.2
macro_rules! give_six {
() => {
6
};
}
fn main() {
let six = give_six!();
println!("{}", six);
}
Use the minimal give_six! listing to see a complete declarative macro and its call. section 22.2


