Declarative macros (macro_rules!) for code generation

14485
0

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.