Skip to main content
Be Bitwise
RustAdvanced Rust Patterns

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!

rust
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:

FragmentMatchesExample
$x:exprExpression42, x + 1
$x:identIdentifierfoo, my_var
$x:tyTypei32, Vec<String>
$x:patPatternSome(x), _
$x:stmtStatementlet x = 1;
$x:blockBlock{ x + 1 }
$x:itemItemfn foo() {}
$x:literalLiteral42, "hello"
$x:ttToken treeAnything

Repetition Patterns

Where macros really earn their keep is repetition:

rust
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.

Try itAdd a trailing comma, vec_of![1, 2, 3,], and check that the expansion doesn't change.
Rust (1.40.0)
Key Concept

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:

rust
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:

rust
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:

rust
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.

Try itTry max!() with no arguments and read the error: no arm matches empty input.
Rust (1.40.0)

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(...)]

rust
// Usage:
#[derive(Debug, Clone, MyTrait)]
struct Point {
x: f64,
y: f64,
}

Attribute macros: Transform items with #[my_attribute]

rust
#[route(GET, "/")]
fn index() -> String {
"Hello!".to_string()
}

Function-like macros: Called like my_macro!(...)

rust
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:

rust
// 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.