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
