Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Optional Parameters

The ? repetition operator can be used for optional parameters, but in older Rust editions (2018 and 2015) it must be emulated; this can be done by defining multiple matcher arms that cascade. Their right-hand sides may reuse each other via recursion, which is a common pattern in declarative macros regardless of edition.

// Copyright 2026 Google LLC
// SPDX-License-Identifier: Apache-2.0

macro_rules! log {
    // Single parameter:
    ($msg:literal) => {
        // Recurse instead of `println!("{}:{}: {}", file!(), line!(), $msg)`:
        log!($msg, )
    };
    // With optional formatting parameters:
    ($msg:literal, $($params:expr),*) => {
        println!(concat!("{}:{}: ", $msg), file!(), line!(), $($params),*)
    };
}

fn main() {
    log!("my message");
    log!("my message with param {}!", 123);
}
This slide should take about 5 minutes.
  • Highlight how concat! is used at compile time to combine the file/line prefix with the user’s log message literal.
  • Recall that the order of arms is significant, just like in a match. The compiler matches sequentially, and if a broader arm is placed above a narrower one, the narrower arm may never be reached.