🦀 Rust Intermediate

What is the difference between procedural macros and declarative macros in Rust?

Answer

Declarative macros (macro_rules!) match against patterns in the source code and expand to Rust code based on the matching arms, similar to hygienic textual substitution. They operate on tokens and are defined in terms of what patterns to match and what code to emit. Examples: vec![], println!(), assert_eq!(). Procedural macros are actual Rust code (functions) that receive a token stream as input and return a new token stream. They are compiled as a separate crate with proc-macro = true. There are three kinds: #[derive(MyTrait)] (add implementations automatically), #[my_attribute] (transform the attributed item), and my_macro!() (function-like, but with full Rust logic). Procedural macros are more powerful and complex, enabling libraries like Serde, Tokio, and Clap.