Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ DESIGN, SAFETY & SHIPPING
BUILD NOTE 49 / 53

Generate a pattern, keep it readable.

Recognize macro expansion and build a small macro_rules tool.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Macros operate on token patterns before normal type checking of the expanded code. macro_rules! is useful for small repeated syntactic patterns such as constructing a collection, while derive macros generate trait implementations. A function should remain your first choice when ordinary typed parameters express the problem. Macro expansion errors can point into generated code, so keep macro interfaces narrow. The ! distinguishes a macro invocation such as vec! or println! from a function call.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/macros/src/main.rs
macro_rules! labels {
    ($($item:expr),* $(,)?) => { vec![$($item.to_string()),*] };
}
fn main() {
    let values = labels!["build", 42, true];
    println!("{values:?}");
}
↳ EXPECTED OUTPUT
["build", "42", "true"]
  1. 1

    The repetition accepts comma-separated expressions.

  2. 2

    Each expression is converted to String.

  3. 3

    The optional final comma is supported explicitly.

From the extracted rust-workbench folder
cargo run -p lesson_macros

03 Mind the boundary

04 Your next build

A SMALL MISSION

Create a macro that produces a pair of independently supplied expressions, then test it.

Reveal one possible solution +
solutions/macros/src/main.rs
macro_rules! pair {
    ($a:expr, $b:expr) => {
        ($a, $b)
    };
}
fn main() {
    assert_eq!(pair!(2 + 1, "ready"), (3, "ready"));
}

05 Check your reasoning

QUICK SIGNAL CHECK

When is a normal function preferable to a macro?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.