Variadic arguments let a call provide a number of arguments determined at the call site. Rust functions do not support them directly, but declarative macros can accept different numbers of inputs and generate the corresponding code. section 2.2.1
A macro-based solution follows this pattern:
- Define separate macro patterns for the supported argument counts. section 2.2.1
- Forward each pattern to an ordinary function, supplying defaults where needed. section 2.2.1
- Expose the macro from its module; newer Rust code should prefer a use declaration for reexporting it over older #[macro_use] usage. section 2.2.1
Greeting with an optional salutation
A greeting macro can accept either greeting!("Sam") or greeting!("Sam", "Heya"). The first form expands to a call using "Hello"; the second forwards the custom salutation. This provides default-argument behavior alongside variable arity without creating differently named functions. section 2.2.1
Listing 2.2 Greeting people, with defaults, in greeting.rs
pub fn base_greeting_fn(name: &str, greeting: &str) -> String {
format!("{}, {}!", greeting, name)
}
macro_rules! greeting {
($name:literal) => {
base_greeting_fn($name,"Hello")
};
($name:literal,$greeting:literal) => {
base_greeting_fn($name,$greeting)
}
}
Inspect the greeting macro and its ordinary base function to see how each accepted call form expands. section 2.2.1







