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.
let name = "Rust";
let message = format!("Hello, {name}!");
assert_eq!(message, "Hello, Rust!");Same syntax, different destination
Section titled “Same syntax, different destination”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.
When format! is the right tool
Section titled “When format! is the right tool”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.
Runtime format strings are not supported
Section titled “Runtime format strings are not supported”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.
format! vs to_string()
Section titled “format! vs to_string()”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!.