How to make a macro that makes a macro that wraps format!

⚓ Rust    📅 2025-09-28    👤 surdeus    👁️ 10      

surdeus

Warning

This post was published 113 days ago. The information described in this article may have changed.

It is possible to make a macro that wraps format!:

macro_rules! my_format {
    ($($arg:tt)*) => {
        format!($($arg)*)
    }
}

Testing, this out with cargo expand, both format! and my_format! expand exactly the same.

Additionally, it's also possible to make macros that produce macros. The problem I when I create a macro that produces macros that wrap format!:

macro_rules! make_format {
    ($name:ident) => {
        macro_rules! $name {
            ($($arg:tt)*) => {
                format!($($arg)*)
            };
        }
    }
}

make_format!(my_format);

Theoretically, this code should do the exact same thing as the example above but in reality it produces the following compiler error:

error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
  --> src/main.rs:10:15
   |
10 |             ($($arg:tt)*) => {
   |               ^^^^^^^^^

How do I fix this?

3 posts - 2 participants

Read full topic

🏷️ Rust_feed