Rust format strings - syntax, width, precision, and traits
A Rust format string mixes literal text with replacement fields. The smallest field is {}: it selects the next argument and formats it with Display. Add syntax after : when you need width, alignment, precision, flags, or a different formatting trait.
assert_eq!(format!("Hello, {}!", "Rust"), "Hello, Rust!");Rust format string syntax
Section titled “Rust format string syntax”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}");Fix invalid format string errors
Section titled “Fix invalid format string errors”Rust parses the format string at compile time. Unmatched braces or malformed replacement fields therefore stop compilation instead of becoming a runtime formatting failure.
fn main() {
println!("{");
}The failure above is compiled intentionally in CI and must continue to produce an invalid format string diagnostic. When you need literal braces in the output, escape them as {{ and }} rather than leaving a single brace in the format text.
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.