Skip to content

format_args! - deferred formatting arguments

format_args! packages a compiler-checked format string and its arguments into fmt::Arguments. It does not build the final heap-allocated String itself, which makes it useful for forwarding formatting work to another API.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/output_pages.rs#output-format-args
fn render(args: std::fmt::Arguments<'_>) -> String {
    std::fmt::format(args)
}

assert_eq!(render(format_args!("{} = {}", "answer", 42)), "answer = 42");

The standard formatting macros are built around format_args!. The returned fmt::Arguments value describes what should be formatted and can be consumed by formatting or writing functions.

That separation matters when a library wants callers to use normal Rust formatting syntax without forcing them to allocate a String before the library decides where the message goes.

Use format! when you need the finished owned String. Use format_args! when an API explicitly accepts fmt::Arguments or when you are building a formatting-aware abstraction.

Passing format_args! directly into the receiving call is the common shape.

fmt::Arguments can borrow the values referenced by the format expression. That makes it different from an owned String: it is not a general-purpose container for formatted text that you can freely store for later.

The standard documentation has specific lifetime rules for format_args!, including temporary lifetime extension in some let initializers. If the goal is simply to keep the text, create a String with format! instead.

Like the other standard formatting macros, format_args! requires a literal format string. The compiler validates the fields and arguments before the program runs.