2.10 Macros

2.10.1 Macros in Rust

Macros provide metaprogramming capabilities.

  • Declarative Macros: Use macro_rules! to define patterns.
macro_rules! say_hello {
    () => {
        println!("Hello!");
    };
}

fn main() {
    say_hello!();
}
  • Procedural Macros: Allow you to generate code using Rust code (more advanced).

2.10.2 The println! Macro

  • println! is a macro because it can accept a variable number of arguments and perform formatting at compile time.

2.10.3 Comparison with C

  • C has preprocessor macros using #define.
#define SQUARE(x) ((x) * (x))

int main() {
    int result = SQUARE(5); // Expands to ((5) * (5))
    printf("%d\n", result);
    return 0;
}
  • C macros are text substitution; Rust macros are more powerful and safer.