macro_rules! in Rust
A declarative macro matches syntax patterns and expands to code.
macro_rules! square {
($n:expr) => {
$n * $n
};
}
macro_rules! named_total {
($label:ident : $($value:expr),+) => {{
let total = 0 $(+ $value)+;
format!("{} = {}", stringify!($label), total)
}};
}
fn main() {
println!("{}", square!(7));
println!("{}", square!(1.5));
println!("{}", named_total!(stars: 3, 2, 1));
}
How it works
$name:exprcaptures an expression,:identa name.- Each rule is a pattern and the tokens it expands into.
#[macro_export]makes it visible outside the crate.
Keywords and builtins used here
exprfnidentletmain
The run, in numbers
- Lines
- 18
- Characters to type
- 316
- Tokens
- 115
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 63 seconds.
Step 2 of 3 in Macros, step 8 of 12 in Modules, tests & macros.