Skip to content

format! - build a String

format! runs Rust’s standard formatting machinery and returns a new owned String. Use it when the formatted text needs to be stored, returned, compared, or passed to an API that requires a string value.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/output_pages.rs#output-format-macro
let name = "Rust";
let message = format!("Hello, {name}!");
assert_eq!(message, "Hello, Rust!");

The fields inside format! are the same fields used by println!, write!, and the rest of the formatting family. Argument capture, width, precision, signs, numeric bases, and formatting traits all behave through the same std::fmt rules.

What changes is the result: format! gives you the finished String instead of writing to stdout or an existing destination.

Use it when ownership of the text is useful:

  • build a message to return from a function
  • create a key or label
  • construct a value required by an API that accepts String
  • keep the result for later use

If the next operation is immediately writing these formatted bytes into an existing destination, write! can avoid the intermediate String.

The format string is compiler-checked and must be a string literal. You cannot pass an arbitrary runtime string and ask format! to interpret replacement fields inside it.

That restriction lets Rust validate formatting syntax and argument compatibility at compile time.

For one value with its normal Display representation, .to_string() is often simpler. format! becomes useful when literal text, multiple arguments, or a non-default format specification is part of the result.

If you need to pass formatting arguments through an API without first allocating the final String, see format_args!.