Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ways To Define Macros

There are two separate ways of implementing macros in Rust. Each has distinct advantages and trade-offs:

FeatureDeclarative MacrosProcedural Macros
UsageFunction-like macros onlyAll three kinds (Derive, Attr, Function-like)
LocationImplemented within your normal crateMust be defined in a separate proc-macro crate
Pros- Low boilerplate
- No extra compilation step
- Easy to write and reuse
- Extremely powerful and expressive
- Written in standard Rust
- Full programmatic control
Cons- Bespoke pattern-matching syntax
- Cannot inspect arbitrary token structures
- Can slow down build time
- Substantial boilerplate required
HygienePartially/mixed hygienic by defaultConfigurable / custom hygiene
This slide should take about 5 minutes.
  • Explain that procedural macros are literally compiled as libraries and executed inside the compiler while compiling the consuming code. This is why they require a separate crate.
  • Emphasize that you should always prefer declarative macros for simple code generation due to their much smaller impact on build times.