2.11 Macros
Macros in Rust are more powerful than C preprocessor macros. They perform syntactic transformations on the input code at compile time.
2.11.1 Declarative and Procedural Macros
- Declarative (
macro_rules!
): Pattern-based expansions. - Procedural: Written in Rust, allowing more complex code generation.
macro_rules! say_hello { () => { println!("Hello!"); }; } fn main() { say_hello!(); }
2.11.2 The println!
Macro
println!
handles compile-time formatting, making it safer than C's printf
(which relies on matching format specifiers to argument types).
2.11.3 Comparison with C
#define SQUARE(x) ((x) * (x))
C macros are text substitutions. Rust macros work with the language's syntax tree, avoiding many pitfalls of textual substitution.