Format strings
A Rust format string mixes literal text with replacement fields. The smallest field is {}: it selects the next argument and formats it with Display.
assert_eq!(format!("Hello, {}!", "Rust"), "Hello, Rust!");Anatomy of a field
Section titled “Anatomy of a field”The official grammar defines a field as an optional argument followed by an optional format specification:
{ [argument] [ : [[fill]align][sign][#][0][width][.precision][type] ] }The colon only introduces formatting options. With no explicit argument, Rust consumes the next argument. An integer selects a positional argument; an identifier selects a named argument or captures a variable from scope.
let language = "Rust";
assert_eq!(format!("{language} {0}", "prints"), "Rust prints");Width is a minimum, not a forced size. Short values are padded; longer values remain intact.
assert_eq!(format!("|{:>8}|", "rust"), "| rust|");
assert_eq!(format!("|{:*^8}|", "rust"), "|**rust**|");Width can come from another usize argument by adding $:
assert_eq!(format!("|{:width$}|", "rust", width = 8), "|rust |");Precision
Section titled “Precision”Precision means decimal places for floating-point values and maximum output width for strings. Integral formatters ignore it.
assert_eq!(format!("{:.2}", 3.14159), "3.14");
assert_eq!(format!("{:.4}", "rustacean"), "rust");Escaping braces
Section titled “Escaping braces”Double a brace to emit it literally: {{ becomes { and }} becomes }.
assert_eq!(format!("{{value}}"), "{value}");Go deeper
Section titled “Go deeper”- Arguments, positions, and captured variables
- Width, alignment, and fill
- Precision
- Binary, octal, hexadecimal, and exponent formatting
- Signs and zero padding
- Alternate formatting with
# - Escaping braces
- Exact format specifier grammar
Use the Rust Format Explorer to split a field into its grammar tokens.