liveBook · Manning

Variadic arguments

As explained in Write Powerful Rust Macros

Variadic arguments are function-call arguments whose number is determined at the call site rather than fixed by the declaration.

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

How Write Powerful Rust Macros covers it

How deep it goes
Demonstrates the function limitation and implements multiple macro call forms, but does not detail compiler internals.
Examples
Uses a vector macro and a greeting macro supporting a name alone or a name plus custom salutation.
What you can do after
Build it from scratch with a declarative macro that accepts multiple call forms and supplies a default argument.
How it connects
Connects variadic arguments with functions, macros, default arguments, and declarative macros.

Also explained in

Compare how 8 books explain variadic arguments →

Related concepts

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