Declarative Macros (`macro_rules!`)
Learn to write declarative macros for abstracting repetitive code patterns and generating code at compile time.
What are Rust Macros?
Macros are a way to write code that writes code! They're like functions, but they operate on syntax trees (the structure of your code) instead of values.
- They help abstract repetitive code.
- They enable Domain Specific Languages (DSLs) within Rust.
- They run at compile time, expanding into regular Rust code before compilation.
Declarative Macro Syntax
Rust's declarative macros use the macro_rules! keyword. They define a set of rules that match specific patterns of Rust code.
Think of it as pattern matching for code snippets. When the compiler sees a macro invocation, it tries to match the input to one of the rules you've defined.
All lessons in this course
- Declarative Macros (`macro_rules!`)
- Procedural Macros: Derive, Function
- Interacting with Unsafe Rust