macro
Generate named items with ident and item
Use ident for names and item for complete declarations. Capturing the name lets a caller choose the generated function name. Expected stdout (not executed): '15\n' Common mistake: An arbitrary expression cannot be substituted where a function name is required.
Formal Syntax & Structure
rust syntaxrust
$name:ident / $item:itemWorking Example
Example Snippetrust
macro_rules! constant_fn { ($name:ident, $value:expr) => { fn $name() -> i32 { $value } }; }macro_rules! keep_item { ($item:item) => { $item }; }constant_fn!(limit, 12);keep_item!(fn bonus() -> i32 { 3 });fn main() { println!("{}", limit() + bonus()); }