Declarative macros (macro_rules!) for code generation
Marcus Chen
Jan 2026
1 tab
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
}
create_function!(foo);
create_function!(bar);
fn main() {
foo();
bar();
}
1 file · rust
Explain with highlit
Declarative macros (macro_rules!) let you write code that writes code, reducing boilerplate. They pattern-match on token trees and expand at compile time. I use them for repetitive patterns like implementing traits for multiple types or generating test cases. Macros are hygienic: they don't accidentally capture variables from the calling context. The syntax takes some getting used to ($(...)* for repetition, $var:ty for type arguments), but it's powerful once you learn it. For complex code generation, procedural macros (derive, attribute, function-like) are more flexible but harder to write. I reach for macro_rules! when I need simple repetition and procedural macros when I need to parse attributes or introspect types.