Blog

Part 29 · Declarative Macros in Rust: macro_rules! Step by Step

A macro is code that writes code before the compiler checks it. This part shows why println! and vec! are macros, how to write your own with macro_rules!, how repetition and hygiene work, and when a plain function is the better choice.

Since Part 1 you’ve typed println! with a ! at the end. The ! means it’s a macro: code that the compiler expands into more code before it checks types and builds the program. In this part we write our own macros with macro_rules!.

We cover the macros you already use and why they can’t be functions, the parts of a macro_rules! rule, repetition, hygiene, macros that generate structs, recursion, and how to see what a macro does. We finish with when a function is the better tool. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

Read this program and decide what happens before you scroll down:

fn main() {
    let name = "Ana";
    println!("{} is {} years old", name);
}

It doesn’t print Ana is years old, and it doesn’t crash. It doesn’t compile:

error: 2 positional arguments in format string, but there is 1 argument

The compiler read the text inside the quotes, counted two {}, and counted one value after it. A function can’t do that. A function gets its arguments when the program runs, and by then it’s too late to refuse to build. println! is a macro, so it runs while the program compiles. It looks at the format string, checks it against the arguments, and only then writes the code that prints.

Notice there’s no error code this time. Errors that come from a macro often don’t have one.

Macros you’ve already used

Here are the four macros you’ve met most, in one program:

fn main() {
    let name = "Ana";
    let age = 31;
    println!("{name} is {age}");
    println!("{} is {} next year", name, age + 1);

    let line = format!("{name}:{age}");
    let mut scores = vec![90, 75];
    scores.push(60);
    let zeros = vec![0; 3];

    assert_eq!(scores.len(), 3);
    println!("{line} {scores:?} {zeros:?}");
}

It prints:

Ana is 31
Ana is 32 next year
Ana:31 [90, 75, 60] [0, 0, 0]

Each of them does something a Rust function can’t:

  • A different number of arguments each time. println! took two values on one line and none on another. A Rust function has a fixed list of parameters. There’s no “any number of arguments” form.
  • A string checked at compile time. println! and format! read the format string while compiling, as we just saw. They also find name and age by the names written inside {name} and {age}.
  • Its own little syntax. vec![0; 3] means “three zeros”. That’s not a Rust expression you could pass to a function. The macro defines what ; means inside its brackets.
  • The text of your code. When assert_eq! fails, it prints both values, and assert! prints the expression you wrote. Part 19 used both. A function only ever sees values, never the code that made them.

You can call a macro with (), [] or {}. They all work the same. By habit we use [] for vec!, {} for macros that define items, and () for the rest.

Your first macro_rules!

macro_rules! defines a macro. Here’s one with a single rule:

macro_rules! square {
    ($x:expr) => {
        $x * $x
    };
}

fn square_fn(x: i32) -> i32 {
    x * x
}

fn main() {
    println!("{}", square!(7));
    println!("{}", square!(2 + 1));
    println!("{}", square_fn(2 + 1));
}

It prints:

49
9
9

A rule has two halves with => between them:

  • the matcher, ($x:expr), on the left. It describes what the call must look like. $x is a metavariable, a name the macro gives to a piece of the input. expr says that piece must be an expression.
  • the transcriber, { $x * $x }, on the right. It’s the code the call turns into. Every $x in it is replaced by whatever $x matched.

So square!(7) turns into 7 * 7. The compiler then checks and compiles 7 * 7 as if you’d typed it.

The second line is worth a look. square!(2 + 1) printed 9, not 2 + 1 * 2 + 1, which is 5. An expr metavariable stays one unit when it’s pasted in, as if it had brackets round it. If you’ve used C’s #define, you know the bug this avoids. C pastes text. Rust pastes pieces of syntax.

Fragment specifiers

The expr in $x:expr is a fragment specifier. It tells the macro what kind of code to accept. These are the ones you’ll use most:

Specifier Matches Example input
expr an expression 2 + 1, v.len(), "hi"
ident a name total, Meters, area
ty a type i32, Vec<String>
literal a literal 42, "m", true
pat a pattern, as in a match arm Some(_), 1..=9
block a block in braces { n += 1; }
tt one token tree a, +, or anything in matched brackets

There are a few more: stmt, path, item, lifetime, vis and meta. The Rust Reference lists them all. A token is the smallest piece the compiler reads: a name, a number, a +, a ,. A token tree is one token, or a whole bracketed group such as (a, b) counted as one.

Here are five of them at work:

macro_rules! constant_fn {
    ($name:ident, $value:literal) => {
        fn $name() -> i32 {
            $value
        }
    };
}

macro_rules! zero {
    ($t:ty) => {
        <$t>::default()
    };
}

macro_rules! is_a {
    ($value:expr, $pattern:pat) => {
        matches!($value, $pattern)
    };
}

macro_rules! twice {
    ($body:block) => {
        $body;
        $body;
    };
}

constant_fn!(answer, 42);

fn main() {
    println!("answer() = {}", answer());

    let a = zero!(i32);
    let b = zero!(String);
    let c = zero!(Vec<u8>);
    println!("zeros: {a} {b:?} {c:?}");

    println!("'q' is a-z: {}", is_a!('q', 'a'..='z'));
    println!("7 is 1..=5: {}", is_a!(7, 1..=5));

    let mut n = 0;
    twice!({
        n += 1;
        println!("n is {n}");
    });
}

It prints:

answer() = 42
zeros: 0 "" []
'q' is a-z: true
7 is 1..=5: false
n is 1
n is 2

constant_fn! made a whole function, and its name came from the call. zero! took a type and called default on it, the Default trait from Part 14. is_a! passes its pattern on to matches!, a standard macro that says whether a value fits a pattern. twice! pasted the same block in two times, so its code ran twice.

A plain function can’t take a pattern, and it can’t create a new function with a name you chose. (Generics from Part 15 and closures from Part 16 come close for the other two, zero! and twice!.)

Several rules, tried from the top

A macro can have several rules, separated by ;. The compiler tries them from the top and uses the first one that matches the whole call:

macro_rules! describe {
    () => {
        String::from("nothing")
    };
    ($x:literal) => {
        format!("the literal {}", $x)
    };
    ($x:expr) => {
        format!("an expression worth {}", $x)
    };
    ($($x:expr),+) => {
        String::from("a list")
    };
}

fn main() {
    let n = 4;
    println!("{}", describe!());
    println!("{}", describe!(5));
    println!("{}", describe!(n + 1));
    println!("{}", describe!(1, 2, 3));
}

It prints:

nothing
the literal 5
an expression worth 5
a list

5 is a literal, so the second rule took it. n + 1 isn’t a literal, so the second rule failed and the third took it. 5 is also an expression, so the order matters here. Put the expr rule above the literal rule, and the literal rule would never be reached.

The last rule uses repetition, which is the next section. When no rule matches at all, you get the error in the first worked example below.

Repetition

vec! accepts any number of items. Your own macro can too. In a matcher, $( ... ),* means “this, any number of times, with commas between”. In the transcriber, $( ... )* means “write this out once for each match”. Here is a small vec! of our own:

#![allow(unused_mut, clippy::vec_init_then_push)]

macro_rules! my_vec {
    ( $( $x:expr ),* ) => {{
        let mut v = Vec::new();
        $( v.push($x); )*
        v
    }};
}

fn main() {
    let empty: Vec<i32> = my_vec![];
    let nums = my_vec![1, 2, 3];
    let words = my_vec!["to", "be"];
    println!("{empty:?} {nums:?} {words:?}");
}

It prints:

[] [1, 2, 3] ["to", "be"]

Notice the double braces in {{ ... }}. The outer pair belongs to the rule and isn’t part of the output. The inner pair is a real block in the expanded code. A block is an expression, so the whole let mut v ... v becomes one value you can assign. Without it, let nums = my_vec![1, 2, 3]; would expand to several statements after let nums =, and that doesn’t parse.

The #![allow(...)] line at the top turns off two lints for this file. It’s there because lints check the expanded code, not the macro, and the series builds every program with Clippy’s warnings treated as errors. my_vec![] expands to a let mut v that’s never changed, so mut is unused. And Clippy sees Vec::new() followed by push calls and suggests writing vec![...] instead. That’s good advice anywhere except inside our own vec!. We tried putting the allow on the let line inside the macro instead. That silenced the first lint but not the second, because Clippy checks that one at the level of the code around the call. The standard library’s real vec! doesn’t push one item at a time, so it never meets this problem.

The animation steps through my_vec![1, 2, 3].

the call the matcher my_vec![ 1 , 2 , 3 ] $( $x:expr ),* $x, one per repetition $x = 1 $x = 2 $x = 3 the transcriber { let mut v = Vec::new(); $( v.push($x); )* v } the expanded code { let mut v = Vec::new(); v } v.push(1); v.push(2); v.push(3); $x: nothing bound yet $x: 1 $x: 1, 2 $x: 1, 2, 3 (three repetitions) expanded: the parts outside $( )* expanded: one v.push line for each $x my_vec![1, 2, 3]: the tokens go to the matcher first repetition: $x:expr matches 1, then the comma it goes round again: $x matches 2 $x matches 3; no comma follows, so matching stops the transcriber: code outside $( )* is copied once $( v.push($x); )* is written out once per value of $x

The matcher binds $x once per repetition. The transcriber copies its plain parts once, and writes the part inside $( )* once for each value of $x.

Here are those steps in words, in case the animation doesn’t play for you:

  1. The compiler hands the tokens of my_vec![1, 2, 3] to the macro, and they’re tried against the matcher $( $x:expr ),*.
  2. The first time round the repetition, $x:expr matches 1. Then the matcher sees the comma, so it goes round again.
  3. The second time round, $x matches 2, followed by another comma.
  4. The third time round, $x matches 3. No comma follows, so the repetition ends. $x now stands for three values: 1, 2 and 3.
  5. The transcriber is used. The code outside $( )* is copied once: the opening brace, let mut v = Vec::new();, the final v and the closing brace.
  6. The part inside $( v.push($x); )* is written out once for each value of $x. That gives v.push(1);, v.push(2); and v.push(3);, in order. The result is an ordinary block that the compiler type-checks like any other code.

The repetition operators

There are three ways to repeat, and you can choose the separator:

  • $( ... ),* is zero or more, separated by commas. my_vec![] matched with zero.
  • $( ... ),+ is one or more. Use it when an empty call makes no sense.
  • $( ... )? is zero or one, with no separator.
  • The separator can be another token, such as ;, or none at all: $( ... )*.

One thing $( $x:expr ),* doesn’t accept is a comma after the last item. my_vec![1, 2, 3,] fails with unexpected end of macro invocation, because after a comma the matcher wants another expression and finds nothing. People write that trailing comma all the time, especially when a list runs over several lines. Add $(,)? to the end of the matcher, “an optional comma”, and the trailing comma works. Exercise 2 asks you to do exactly that.

Hygiene: the macro’s names stay inside the macro

Here the macro makes a variable called x, and so does the caller:

macro_rules! double_it {
    ($e:expr) => {{
        let x = $e;
        x * 2
    }};
}

fn main() {
    let x = 10;
    let y = double_it!(x + 1);
    println!("x = {x}, y = {y}");
}

It prints:

x = 10, y = 22

The expansion contains let x = x + 1;, which looks like it should clash. It doesn’t. Rust remembers where each name was written. The x in let x was written inside the macro. The x in x + 1 was written by the caller. They’re different variables, even though they’re spelled the same. This is called hygiene. A macro’s own local names can’t capture yours, and yours can’t leak into it.

It works the other way too. A macro can’t reach a local variable just because the caller happens to have one with that name:

macro_rules! show_total {
    () => {
        println!("{}", total)
    };
}

fn main() {
    let total = 5;
    show_total!();
}

It prints:

error[E0425]: cannot find value `total` in this scope
 --> src/main.rs:3:24
  |
3 |         println!("{}", total)
  |                        ^^^^^ not found in this scope
...
9 |     show_total!();
  |     ------------- in this macro invocation
  |
help: an identifier with the same name exists, but is not accessible due to macro hygiene

The help: line says it plainly. If the macro should work on the caller’s variable, the caller has to pass the name in. A name that arrives through an ident belongs to the caller, so the macro can read it, change it, or even create it:

macro_rules! show {
    ($name:ident) => {
        println!("{} = {}", stringify!($name), $name)
    };
}

macro_rules! make_counter {
    ($name:ident) => {
        let mut $name = 0;
        $name += 1;
    };
}

fn main() {
    let total = 5;
    show!(total);

    make_counter!(clicks);
    clicks += 1;
    show!(clicks);
}

It prints:

total = 5
clicks = 2

make_counter!(clicks) created a variable that the caller can use on the next line, because the name clicks came from the caller. stringify! turns its input into a string, here the variable’s name. We’ll see more of it below.

Hygiene in macro_rules! covers local variables and labels. Function names, types and other items aren’t hidden the same way. constant_fn!(answer, 42) above made a function that main could call, and that’s the point of such a macro.

Generating a struct and its impl

Macros can write whole items: structs, impls, functions. This is where they save the most typing. A newtype is a struct with one field that wraps another type, so that the compiler keeps two kinds of number apart. Writing the struct, the derive and a Display impl for each one gets dull, so a macro writes them:

use std::fmt;

macro_rules! newtype {
    ($name:ident, $inner:ty, $unit:literal) => {
        #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
        struct $name($inner);

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{} {}", self.0, $unit)
            }
        }
    };
}

newtype!(Meters, f64, "m");
newtype!(Seconds, f64, "s");

fn speed(d: Meters, t: Seconds) -> f64 {
    d.0 / t.0
}

fn main() {
    let d = Meters(100.0);
    let t = Seconds(9.58);
    println!("{d} in {t}");
    println!("{:.2} m/s", speed(d, t));
    println!("{:?}", Meters(1.5) < Meters(2.0));
}

It prints:

100 m in 9.58 s
10.44 m/s
true

Two calls gave us two structs and two Display impls. Because Meters and Seconds are now different types, speed(t, d) with the arguments swapped would be a type error (E0308), not a wrong answer. The macro wrote code, and then the compiler checked that code as usual.

Recursion: a macro that calls itself

A transcriber can call a macro, including the one it’s in. That gives you recursion. This count! counts the tokens it’s given:

macro_rules! count {
    () => {
        0usize
    };
    ($head:tt $($tail:tt)*) => {
        1usize + count!($($tail)*)
    };
}

macro_rules! max {
    ($x:expr) => {
        $x
    };
    ($x:expr, $($rest:expr),+) => {{
        let a = $x;
        let b = max!($($rest),+);
        if a > b { a } else { b }
    }};
}

fn main() {
    println!("{}", count!());
    println!("{}", count!(a b c));
    println!("{}", count!(apple (two words) "three"));
    println!("{}", max!(3));
    println!("{}", max!(3, 9, 4, 1));
}

It prints:

0
3
3
3
9

count!(a b c) matches the second rule with $head as a and the rest as b c. It becomes 1usize + count!(b c), then 1usize + 1usize + count!(c), and so on until the empty call hits the first rule and gives 0usize. (two words) counted as one, because a bracketed group is one token tree.

max! peels off the first expression and compares it with the max of the rest. The compiler does the recursion while it builds the program. The finished program has no recursion in it, only nested ifs. Recursion this deep is fine, but it has a limit. The compiler stops expanding after 128 levels by default, and very long inputs to a macro like count! can hit it.

Where a macro can be used

A macro_rules! macro exists from the line it’s defined on, down to the end of the file (or of the mod block it’s in). Use it above its definition and the compiler can’t find it:

fn main() {
    println!("{}", twice!(3));
}

macro_rules! twice {
    ($x:expr) => {
        $x * 2
    };
}

It prints:

error: cannot find macro `twice` in this scope
 --> src/main.rs:2:20
  |
2 |     println!("{}", twice!(3));
  |                    ^^^^^ consider moving the definition of `twice` before this call

This is different from functions, which you can call from anywhere in their module whatever the order. A macro_rules! macro follows the text instead, from its definition downwards. The Rust Reference calls this textual scope. Define macros near the top of a file.

To use a macro from another crate, its author marks it #[macro_export]. That puts it at the root of the crate, whatever module it was written in. Users then import it like anything else, use my_crate::my_vec;, the way Part 18 imported functions. Inside the same crate, an exported macro can also be named by its path, crate::my_vec!, and then the line order no longer matters:

mod helpers {
    #[macro_export]
    macro_rules! triple {
        ($x:expr) => {
            $x * 3
        };
    }
}

fn main() {
    println!("{}", crate::triple!(14));
}

It prints:

42

Seeing what a macro does

When a macro misbehaves, you want to see the code it wrote. Three tools help.

stringify! turns its input into a string literal, without running it. concat! glues literals into one string literal at compile time. Both are built in:

macro_rules! show {
    ($e:expr) => {
        println!("{} = {:?}", stringify!($e), $e)
    };
}

const VERSION: &str = concat!("v", 1, ".", 95, "-", true);

fn main() {
    show!(2 + 3 * 4);
    show!("abc".len());
    show!("a,b,c".split(',').count());
    println!("{VERSION}");
}

It prints:

2 + 3 * 4 = 14
"abc".len() = 3
"a,b,c".split(',').count() = 3
v1.95-true

show! is a tiny version of what assert! does when it prints the expression that failed. You can drop a println! with stringify! into a macro you’re writing, to see what each metavariable matched.

cargo expand shows the whole program after every macro has been expanded. It’s a third-party tool, not part of Rust, and you install it with cargo install cargo-expand. It asks the compiler for the expanded code with an option, -Zunpretty=expanded, that stable Rust doesn’t offer on its own, so check its README for the setup it needs. We didn’t install it for this series, so we won’t show its output. It’s worth knowing about once your macros get bigger. It also shows you what println! and #[derive] really turn into, which is a good way to lose an afternoon.

When a function is better

Most of the time, a function or a generic does the job better than a macro:

  • Error messages. A function’s type errors point at the call. A macro’s errors point into code you didn’t write, or they say “no rules expected” and leave you to work out why.
  • Readability. fn square<T: Mul<Output = T> + Copy>(x: T) -> T says what goes in and what comes out. A matcher says what the input looks like, not what it means.
  • Editor support. Editors can complete, rename and jump to definitions through functions easily. Inside a macro’s input they often can’t.
  • It’s checked once. A generic function is type-checked once, when it’s defined (Part 15). A macro’s output is checked again at every call, and a mistake in it shows up only when someone calls it in a new way.

So reach for a macro only when a function can’t do the job:

  • a different number of arguments each time (my_vec!, max!);
  • making new items or names (newtype!, constant_fn!);
  • working on code as text (stringify!, assert!);
  • a small syntax of your own (vec![0; 3], hashmap!{ "a" => 1 }).

square! from the start of this part is a bad macro. square_fn, or a generic version of it, is better in every way.

Procedural macros, in one paragraph

macro_rules! macros are declarative: you describe input patterns and the output for each. Rust has a second kind, procedural macros. A procedural macro is a Rust function that runs inside the compiler. It takes the tokens of your code and returns new tokens. #[derive(Debug)] from Part 14 works this way, and so do #[derive(Serialize)] in the serde crate and #[derive(Error)] in thiserror. A procedural macro must live in its own crate, marked proc-macro = true in Cargo.toml, and in practice it’s written with the syn crate (to parse Rust code) and the quote crate (to write it). This series uses only the standard library, so we stop here. The idea is the same as macro_rules!: code in, more code out, before type checking.

Worked example: a map literal, and “no rules expected”

Rust has vec! but no built-in macro for a map. Let’s write btreemap!{ "a" => 1, "b" => 2 }. We use a BTreeMap from Part 13, so the output comes out sorted by key:

use std::collections::BTreeMap;

macro_rules! btreemap {
    ( $( $key:expr => $value:expr ),* $(,)? ) => {{
        let mut map = BTreeMap::new();
        $( map.insert($key, $value); )*
        map
    }};
}

fn main() {
    let ages = btreemap! {
        "Ben" => 25,
        "Ana" => 31,
        "Cai" => 19,
    };
    println!("{ages:?}");
}

It prints:

{"Ana": 31, "Ben": 25, "Cai": 19}

The repetition now holds two metavariables, $key and $value, with a literal => between them. Inside a matcher, anything that doesn’t start with $ must appear in the call exactly as written. The $(,)? at the end accepts the trailing comma after "Cai" => 19.

Someone coming from Python or JSON will try a colon instead of =>:

use std::collections::BTreeMap;

macro_rules! btreemap {
    ( $( $key:expr => $value:expr ),* $(,)? ) => {{
        let mut map = BTreeMap::new();
        $( map.insert($key, $value); )*
        map
    }};
}

fn main() {
    let ages = btreemap! { "Ana": 31 };
    println!("{ages:?}");
}

It prints:

error: no rules expected `:`
  --> src/main.rs:12:33
   |
 3 | macro_rules! btreemap {
   | --------------------- when calling this macro
...
12 |     let ages = btreemap! { "Ana": 31 };
   |                                 ^ no rules expected this token in macro call
   |
note: while trying to match `=>`

Read it from the bottom. The note: says what the matcher was looking for: =>. The ^ points at what it found instead: the : after "Ana". The first line names the macro whose rules were tried. “No rules” means every rule of the macro was tried, and none of them fit the call.

This error has no error code, so there’s no rustc --explain page. The fix is nearly always to compare the call with the matcher, token by token, from the place the ^ points to.

Worked example: a checklist with ;

The separator in a repetition doesn’t have to be a comma. This macro takes conditions separated by ;, like statements, and reports each one by name:

macro_rules! checklist {
    ( $( $cond:expr );+ $(;)? ) => {{
        let mut failed = 0;
        $(
            let ok = $cond;
            if !ok {
                failed += 1;
            }
            println!("[{}] {}", if ok { "x" } else { " " }, stringify!($cond));
        )+
        failed
    }};
}

fn main() {
    let name = String::from("Ana");
    let age = 31;
    let tags: Vec<&str> = Vec::new();

    let failed = checklist! {
        !name.is_empty();
        age >= 18;
        !tags.is_empty();
        name.len() < 20;
    };
    println!("{failed} failed");
}

It prints:

[x] !name.is_empty()
[x] age >= 18
[ ] !tags.is_empty()
[x] name.len() < 20
1 failed

A few things to notice:

  • $(;)? again allows a trailing separator, so the last condition can end with ; like the others.
  • The repetition in the transcriber holds several statements. Each copy gets its own let ok. That’s fine: each one shadows the one before, as in Part 2.
  • stringify!($cond) gives each line its label from the code itself. A function would see only true or false.
  • failed is the macro’s own variable. If the caller also had a failed, hygiene would keep the two apart. Here the caller’s let failed = ... gets the value the block returns.

Tips and traps

  • A missing !. Without the !, Rust reads my_vec[1, 2] as indexing a variable called my_vec, and the error is about syntax, not macros: expected one of ... found ,. Add the !.
  • Statements where an expression is wanted. A transcriber with several statements used as let v = m!(...); fails to parse. Wrap the transcriber in an extra block, {{ ... }}, so it’s one expression.
  • Rules in the wrong order. A broad rule, such as $x:expr or $($t:tt)*, above a narrow one catches everything first. Put the most specific rules at the top.
  • No trailing comma. $( $x:expr ),* rejects [1, 2, 3,] with “unexpected end of macro invocation”. Add $(,)? at the end of the matcher.
  • Using a macro before its definition. You get “cannot find macro in this scope” and a hint to move the definition. Define macros at the top of the file, or export them and call them by path.
  • A local name the macro expected to see. Hygiene hides the caller’s local variables from the macro (E0425). Pass the name in as an ident.
  • Lints see the expanded code. A warning can point into your transcriber but only happen for one kind of call, such as an unused mut when a repetition matched nothing. Read the in this macro invocation line to find the call, then fix the transcriber, or allow that one lint.
  • A macro where a function would do. If every call has the same number of arguments and only values go in, write a function. You’ll get better errors and better editor support.

A macro writes code before the compiler checks it, so use one only when a function can’t do the job.

Exercises

Exercise 1. Write a min! macro that takes one or more expressions, separated by commas, and gives the smallest. min!(4) is 4 and min!(5, 2, 8) is 2. Use recursion, like max! above.

Exercise 2. This macro turns each item into a String and returns them in an array. It rejects a trailing comma. Change only the matcher so that the call in main works.

macro_rules! strings {
    ( $( $x:expr ),* ) => {
        [ $( $x.to_string() ),* ]
    };
}

fn main() {
    let s = strings![1, "two", 'c',];
    println!("{s:?}");
}

It prints:

error: unexpected end of macro invocation

Exercise 3. Predict what this prints. Which step does the macro use, and which total does it change?

macro_rules! bump {
    ($counter:ident) => {
        let step = 10;
        $counter += step;
    };
}

fn main() {
    let step = 1;
    let mut total = 0;
    bump!(total);
    total += step;
    println!("total = {total}, step = {step}");
}
Answers

1. One rule for a single expression, and one that compares the first with the min! of the rest:

macro_rules! min {
    ($x:expr) => {
        $x
    };
    ($x:expr, $($rest:expr),+) => {{
        let a = $x;
        let b = min!($($rest),+);
        if a < b { a } else { b }
    }};
}

fn main() {
    println!("{}", min!(4));
    println!("{}", min!(5, 2, 8));
    println!("{}", min!(2.5, -1.0));
}

It prints:

4
2
-1

2. Add $(,)? after the repetition. It matches one comma or none, and the transcriber ignores it:

macro_rules! strings {
    ( $( $x:expr ),* $(,)? ) => {
        [ $( $x.to_string() ),* ]
    };
}

fn main() {
    let s = strings![1, "two", 'c',];
    let t = strings![2.5, true];
    println!("{s:?} {t:?}");
}

It prints:

["1", "two", "c"] ["2.5", "true"]

3. The macro’s let step = 10 is its own variable, so $counter += step adds 10. total came in as an ident, so the macro changes the caller’s total. Then main adds its own step, which is still 1. Hygiene kept the two steps apart.

macro_rules! bump {
    ($counter:ident) => {
        let step = 10;
        $counter += step;
    };
}

fn main() {
    let step = 1;
    let mut total = 0;
    bump!(total);
    total += step;
    println!("total = {total}, step = {step}");
}

It prints:

total = 11, step = 1

What’s next

That’s the last new language feature in the series. In Part 30, we put the pieces together: a multi-threaded key-value server over TCP, with tests, using only the standard library.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.