Macros
Macros are code that writes code. Rust ships two flavours: declarative macros (macro_rules!) drive pattern matching and code generation, while procedural macros handle the heavier transformations. They cut boilerplate, build domain-specific syntax, and let you do things plain functions can't — variadic arguments being the classic example.
Declarative Macros with macro_rules!
macro_rules! say_hello { () => { println!("Hello!"); }; ($name:expr) => { println!("Hello, {}!", $name); };}
fn main() { say_hello!(); // Hello! say_hello!("world"); // Hello, world!}Two arms, matched by pattern. $name:expr swallows any expression.
Fragment Types
Macros pattern-match against different bits of syntax:
| Fragment | Matches | Example |
|---|---|---|
$x:expr | Expression | 42, x + 1 |
$x:ident | Identifier | foo, my_var |
$x:ty | Type | i32, Vec<String> |
$x:pat | Pattern | Some(x), _ |
$x:stmt | Statement | let x = 1; |
$x:block | Block | { x + 1 } |
$x:item | Item | fn foo() {} |
$x:literal | Literal | 42, "hello" |
$x:tt | Token tree | Anything |
Repetition Patterns
Where macros really earn their keep is repetition:
macro_rules! vec_of { ($($element:expr),* $(,)?) => { { let mut v = Vec::new(); $(v.push($element);)* v } };}
fn main() { let v = vec_of![1, 2, 3, 4, 5]; println!("{:?}", v); // [1, 2, 3, 4, 5]}$(...)* is zero or more repetitions, $(...)+ is one or more, and $(,)? lets a trailing comma slide.
A macro is easier to trust once you've seen what it turns into. cargo expand prints the expansion for a whole crate; here, stringify! does a cheap version of the same job by turning the generated tokens back into text. The odd spacing in the printout is the compiler's, not yours.
macro_rules! macros are partially hygienic. A let binding inside the macro won't trample a v the caller already declared — the two live in different syntactic scopes. Items though (functions, structs) defined inside a macro leak out, so they're visible from the call site.
Practical Macros
HashMap literal:
macro_rules! hashmap { ($($key:expr => $value:expr),* $(,)?) => {{ let mut map = std::collections::HashMap::new(); $(map.insert($key, $value);)* map }};}
fn main() { let scores = hashmap! { "Alice" => 92, "Bob" => 78, "Carol" => 95, }; println!("{:?}", scores);}Struct builder:
macro_rules! builder { ($name:ident { $($field:ident : $ty:ty),* $(,)? }) => { struct $name { $($field: $ty,)* }
impl $name { fn new() -> Self { $name { $($field: Default::default(),)* } }
$( fn $field(mut self, value: $ty) -> Self { self.$field = value; self } )* } };}
builder!(Config { host: String, port: u16, debug: bool,});
fn main() { let config = Config::new() .host("localhost".to_string()) .port(8080) .debug(true);}Recursive Macros
Macros can recurse, which is handy for trickier pattern matching:
macro_rules! count { () => (0usize); ($head:tt $($tail:tt)*) => (1usize + count!($($tail)*));}
fn main() { let n = count!(a b c d e); println!("Count: {}", n); // 5}count! peels one token off per step until nothing's left. The same move gives you a max! that takes any number of arguments, which no ordinary Rust function can do.
Procedural Macros Overview
Procedural macros are plain Rust functions that munch a TokenStream and emit a new one. More flexible than macro_rules!, but they have to live in their own crate. Three flavours:
Derive macros: Generate implementations from #[derive(...)]
// Usage:#[derive(Debug, Clone, MyTrait)]struct Point { x: f64, y: f64,}Attribute macros: Transform items with #[my_attribute]
#[route(GET, "/")]fn index() -> String { "Hello!".to_string()}Function-like macros: Called like my_macro!(...)
let sql = sql!(SELECT * FROM users WHERE id = 1);Writing a Simple Derive Macro
Procedural macros live in their own crate, marked with proc-macro = true in Cargo.toml:
// In the proc-macro crate:use proc_macro::TokenStream;use quote::quote;use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]pub fn hello_macro_derive(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident;
let expanded = quote! { impl HelloMacro for #name { fn hello() { println!("Hello from {}!", stringify!(#name)); } } };
TokenStream::from(expanded)}When to Use Macros
Use macros when:
- You need variable numbers of arguments
- You need to generate repetitive code (implementations for many types)
- You want compile-time validation of domain-specific syntax
- Functions cannot express what you need (creating new items, implementing traits)
Avoid macros when:
- A function or generic would work - they are easier to understand and debug
- The macro hides important complexity
- Error messages would be confusing
Macros are sharp tools. They earn their keep, but every macro raises the cognitive bar for everyone reading the code. Use them sparingly.