liveBook · Manning

Macro overloading

As explained in Idiomatic Rust

Macro overloading is the ability of a macro definition system to accept and distinguish different argument forms.

Macro overloading lets a Rust macro accept different argument forms and select an expansion based on the matched pattern. It is useful when a function cannot express the desired syntax. section 5.1.2

Use macro argument matching to:

  • Accept a variable number of arguments with repeated token-tree matches such as $($arg:tt)*. section 5.1.2
  • Define separate matching arms for distinct forms, as format_args! does for one argument versus a format string followed by arguments. section 5.1.2
  • Wrap existing formatting behavior while preserving println!-style calls. section 5.1.2

A variadic formatting wrapper

macro_rules! special_println { ($($arg:tt)*) => { println!("Printed specially: {}", format!($($arg)*)) }; } special_println!("hello world!"); The repeated token-tree matcher accepts the complete argument sequence and forwards it into format!. section 5.1.2

Listing 5.2 format_args! macro definition from the Rust standard library
macro_rules! format_args {
    ($fmt:expr) => {{ /* compiler built-in */ }};
    ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
}

Compare the two macro arms: one matches only a format expression, while the other matches a format expression followed by repeated token-tree arguments. section 5.1.2

How Idiomatic Rust covers it

How deep it goes
Explains repeated token-tree matching and shows multiple macro arms, but stops short of broader pattern-matching details.
Examples
Demonstrates special_println!, format_args!, println!-style calls, and variable-name debugging with var_print!.
What you can do after
Apply macro_rules! patterns to build variadic wrappers and distinguish supported argument forms.
How it connects
Connects macro overloading to variadic arguments, token trees, formatting macros, custom logging, and domain-specific languages.

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.