Define a declarative macro in Rust using the macro_rules! keyword to create reusable code patterns that expand at compile time.
You write a declarative macro using the macro_rules! construct, which defines patterns to match input code and templates to generate output code.
macro_rules! my_macro {
($x:expr) => {
println!("Value: {}", $x);
};
}
fn main() {
my_macro!(42);
}
The macro_rules! keyword starts the definition, followed by the macro name and a body containing pattern-template arms separated by semicolons.
A declarative macro is a tool that lets you write code that generates more code before your program runs. Think of it like a template for a document: you define the structure once, and the computer fills in the blanks every time you use it. This helps you avoid repeating similar code blocks by handling variable inputs automatically.