MacrosAdvanced
1Question 1 of 1
rustWhat are Declarative and Procedural Macros in Rust?
Explanation & Concept
Macros enable metaprogramming (code that writes code at compile-time): • Declarative Macros (`macro_rules!`): Pattern-matching syntax replacements (e.g. `vec![]`, `println!`). • Procedural Macros: Functions that accept TokenStreams as input and output new TokenStreams (Custom Derive, Attribute, Function-like).
Code Example
rust
// Simple declarative macro
macro_rules! say_hello {
() => {
println!("Hello from Rust Macro!");
};
}
fn main() {
say_hello!();
}How It Works & Key Takeaways
Macros expand during compilation before type checking, providing compile-time abstraction without runtime overhead.
Mock Test · 1 Questions · Optional
Ready for Unsafe Rust?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions