medium.com 5 min read Original Source

The Rust Feature That Writes Your Code for You

Every language has macros or something that fills the same role. C has the preprocessor. Java has annotation processors. Python has decorators, though those are different in important ways. Rust’s macro system is in a category of its own. It is more powerful than C’s text substitution, safer, and deeply integrated into the language.

I put off learning macros for a while because they looked like a different language inside Rust. The syntax is unfamiliar and it is easy to find scary-looking macro definitions online that make you think you need a PhD to write one. Most macros you will actually write are straightforward. This article starts from the ground up.

1. What Are Macros and Why Does Rust Have Them?

A macro is code that writes code. When the compiler sees a macro call, it expands it into regular Rust code before compiling. The actual compilation happens on the expanded code.

Rust has macros for a specific reason: the language has no function overloading and no variadic functions. You cannot write a regular function that accepts any number of arguments of different types. Macros can do this. The println! macro is the most obvious example: it accepts a format string and any number of arguments of any printable type.

Without macros you would need a separate function for every combination of argument types and counts. That is not practical.

2. Macros You Already Know

Before writing your own, notice how many built-in macros you have already been using:

println!("hello {}", name);      // formatted printing
vec![1, 2, 3];                    // create a Vec
assert_eq!(a, b);                 // testing equality
format!("value: {}", x);         // build a String
panic!("something went wrong");   // unrecoverable error
todo!();                          // placeholder for unfinished code
dbg!(some_value);                 // print value with file/line info
println!("hello {}", name);      // formatted printing
vec![1, 2, 3];                    // create a Vec
assert_eq!(a, b);                 // testing equality
format!("value: {}", x);         // build a String
panic!("something went wrong");   // unrecoverable error
todo!();                          // placeholder for unfinished code
dbg!(some_value);                 // print value with file/line info

The ! at the end is what distinguishes a macro call from a function call. This is intentional: macros and functions behave differently and Rust wants you to see the difference at a glance.

3. Declarative Macros with macro_rules!

The most common type of macro you will write yourself is a declarative macro. You define patterns and what code to generate for each pattern.

A simple example: a macro that creates a HashMap without the repetitive insert calls:

$value:expr ),* ) => {
{
let mut m = std::collections::HashMap::new();
$( m.insert($key, $value); )*
m
}
};
}
fn main() {
let scores = map! {
"Alice" => 95,
"Bob" => 87,
"Carol" => 92
};
println!("{:?}", scores);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

macro_rules! map {
    ( $( $key:expr => $value:expr ),* ) => {
        {
            let mut m = std::collections::HashMap::new();
            $( m.insert($key, $value); )*
            m
        }
    };
}
fn main() {
    let scores = map! {
        "Alice" => 95,
        "Bob" => 87,
        "Carol" => 92
    };
    println!("{:?}", scores);
}
macro_rules! map {
    ( $( $key:expr => $value:expr ),* ) => {
        {
            let mut m = std::collections::HashMap::new();
            $( m.insert($key, $value); )*
            m
        }
    };
}
fn main() {
    let scores = map! {
        "Alice" => 95,
        "Bob" => 87,
        "Carol" => 92
    };
    println!("{:?}", scores);
}

Breaking down the macro definition:

  • $( $key:expr => $value:expr ),* is the pattern. The $( … ),* means “match this pattern zero or more times, separated by commas.”
  • $key:expr captures any expression and names it key.
  • $value:expr captures any expression and names it value.
  • In the expansion, $( m.insert($key, $value); )* repeats the insert for each matched pair.

This is the kind of macro that saves you from repetitive boilerplate. In Python you might solve this with a dict literal directly, which is cleaner because Python has dict literal syntax. In Rust you would otherwise need five separate .insert() calls.

4. A More Practical Example

Here is a macro for asserting multiple conditions at once:

{
$(
assert!($condition, "Assertion failed: {}", stringify!($condition));
)+
};
}
fn main() {
let x = 5;
let y = 10;
let z = 15;
assert_all!(x < y, y

macro_rules! assert_all {
    ( $( $condition:expr ),+ ) => {
        $(
            assert!($condition, "Assertion failed: {}", stringify!($condition));
        )+
    };
}
fn main() {
    let x = 5;
    let y = 10;
    let z = 15;
    assert_all!(x < y, y < z, x + y == z);
    println!("All assertions passed");
}
macro_rules! assert_all {
    ( $( $condition:expr ),+ ) => {
        $(
            assert!($condition, "Assertion failed: {}", stringify!($condition));
        )+
    };
}
fn main() {
    let x = 5;
    let y = 10;
    let z = 15;
    assert_all!(x < y, y < z, x + y == z);
    println!("All assertions passed");
}

stringify!($condition) converts the expression to a string for the error message. If the assertion x < y fails, the message says “Assertion failed: x < y” which is far more useful than just “assertion failed.”

5. Common Fragment Specifiers

When you capture something in a macro pattern, you tell the compiler what kind of syntax you expect. The most common ones:

  • expr matches any expression: 5 + 3, "hello", some_function()
  • ident matches an identifier: a variable name, function name
  • ty matches a type: i32, String, Vec<u32>
  • stmt matches a statement
  • block matches a block of code { … }
  • literal matches a literal value: 42, "text", true

{
fn $name() -> $return_type $body
};
}
create_fn!(hello, String, {
String::from("Hello from a generated function!")
});
fn main() {
println!("{}", hello());
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

macro_rules! create_fn {
    ($name:ident, $return_type:ty, $body:block) => {
        fn $name() -> $return_type $body
    };
}
create_fn!(hello, String, {
    String::from("Hello from a generated function!")
});
fn main() {
    println!("{}", hello());
}
macro_rules! create_fn {
    ($name:ident, $return_type:ty, $body:block) => {
        fn $name() -> $return_type $body
    };
}
create_fn!(hello, String, {
    String::from("Hello from a generated function!")
});
fn main() {
    println!("{}", hello());
}

This macro generates entire function definitions. The function hello does not exist in the source code directly. The macro creates it at compile time.

6. Derive Macros

The #[derive(...)] attribute you have been using since the early articles is actually a macro:

fmt::Result {
write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}
impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
    }
}
#[derive(Debug, Clone, PartialEq)]
struct Point {
    x: f64,
    y: f64,
}
impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
    }
}

derive(Debug) generates the fmt::Debug implementation automatically. Without the derive, you would need to write:

That is the boilerplate the macro eliminates. In Java the equivalent is @Override or Lombok’s @Data. In Python it is @dataclass. The idea is the same: the compiler generates code you would otherwise write by hand.

The crate serde is one of the most used Rust libraries and it works entirely through derive macros:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    host: String,
    port: u16,
    debug: bool,
}
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    host: String,
    port: u16,
    debug: bool,
}

#[derive(Serialize, Deserialize)] generates all the code needed to convert Config to and from JSON, TOML, YAML, or any other format serde supports. Behind the scenes that is hundreds of lines of code you never have to write.

7. Procedural Macros

Beyond macro_rules!, Rust has procedural macros. These are actual Rust programs that take a token stream as input and return a token stream as output.

There are three kinds:

  • Derive macros (#[derive(MyTrait)])
  • Attribute macros (#[my_attribute])
  • Function-like macros (my_macro!(...) but with more power than macro_rules!)

Writing procedural macros is more complex and requires a separate crate. Most developers use them through libraries rather than writing their own. The tokio::main macro you saw in the async article is a procedural attribute macro.

A simple attribute macro example showing the concept:

TokenStream {
// parse the function, add logging code, return modified function
// … implementation would use the `syn` and `quote` crates
item // simplified
}
// Usage:
#[log_call]
fn my_function() {
// automatically logs entry/exit
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// In a proc-macro crate:
use proc_macro::TokenStream;
#[proc_macro_attribute]
pub fn log_call(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // parse the function, add logging code, return modified function
    // ... implementation would use the `syn` and `quote` crates
    item // simplified
}
// Usage:
#[log_call]
fn my_function() {
    // automatically logs entry/exit
}
// In a proc-macro crate:
use proc_macro::TokenStream;
#[proc_macro_attribute]
pub fn log_call(_attr: TokenStream, item: TokenStream) -> TokenStream {
    // parse the function, add logging code, return modified function
    // ... implementation would use the `syn` and `quote` crates
    item // simplified
}
// Usage:
#[log_call]
fn my_function() {
    // automatically logs entry/exit
}

The full implementation of a procedural macro uses the syn crate to parse Rust code and the quote crate to generate it. When you are ready to go deep on this, those two crates have excellent documentation.

8. When to Use Macros vs Functions

Macros can do things functions cannot:

  • Accept a variable number of arguments of different types
  • Generate code (new functions, impl blocks, struct fields)
  • Work with syntax rather than values

But they have downsides:

  • Harder to read and debug
  • Errors inside macros show confusing locations
  • Cannot be imported as easily as functions

The rule I follow: use a function if a function can do the job. Reach for a macro when you need to generate code, work with varying argument counts, or eliminate repetitive boilerplate that would otherwise be unavoidable.

Summary

Macros in Rust are code generation tools that run at compile time. macro_rules! lets you define pattern-matching macros for common boilerplate. Derive macros automate trait implementations. Procedural macros give you full programmatic control over code generation. You have been using macros since article one. Now you know what they actually are.

What’s Next

Modules, crates, and project structure. How to organize a real Rust project, how Cargo works for managing dependencies, and the conventions the Rust community follows for structuring code as it grows.

Happy coding and safe assembling!

Follow this series and join us in mastering Rust from scratch!