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.
Previous
What is unsafe Rust and what does it allow?
Next
What are derive macros and which common ones does Rust provide?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?