Strings and Text Processing
String Formatting
Rust's formatting machinery (std::fmt) uses compile-time-checked format strings ("{arg:spec}") to control alignment, fill characters, width, numeric precision, sign display, and radix across format!, println!, and write!.
Anatomy of a Format Specifier
{ variable : [fill][align][sign][#][0][width][.precision][type] }
| Specifier Component | Syntax | Effect | Example (x = 42) |
|---|---|---|---|
| Positional / Named | {0}, {name} |
Selects argument by index or variable name | "{x}" -> "42" |
| Alignment & Width | :<w, :^w, :>w |
Left, center, or right-aligns to minimum width w |
"{x:>5}" -> " 42" |
| Fill Character | :*<w, :_>w, :0w |
Pads unused width with custom fill character or 0 |
"{x:05}" -> "00042" |
| Sign | :+ |
Always prefixes positive numbers with + |
"{x:+}" -> "+42" |
| Precision (floats / strings) | :.p |
Decimal places for floats, or max byte/char truncation for &str |
"{3.14159:.2}" -> "3.14" |
| Radix / Base | :x, :X, :b, :o |
Lower hex, upper hex, binary, or octal (add # for 0x/0b/0o prefix) |
"{x:#06x}" -> "0x002a" |
| Trait Selection | (empty), :?, :#?, :e, :p |
Display, Debug, pretty Debug, scientific notation, pointer address |
"{x:?}" -> "42" |
Alignment, Padding, Numeric Radix, and Precision Examples
fn main() {
let name = "compute-node";
let status = 255_u16;
let latency_ms = 12.3456_f64;
// Alignment and fill characters:
println!("|{name:<16}|{name:^16}|{name:>16}|");
println!("|{name:.<16}|");
// Numeric base and zero-padding:
println!(
"dec={status}, hex={status:#06x}, bin={status:#010b}"
);
// Floating-point precision and string truncation:
println!("Latency: {latency_ms:+08.2} ms");
println!("Truncated string (5 chars): '{name:.5}'");
}
|compute-node | compute-node | compute-node|
|compute-node....|
dec=255, hex=0x00ff, bin=0b11111111
Latency: +0012.35 ms
Truncated string (5 chars): 'compu'
Dynamic Width and Precision (width$ and prec$)
You can pass the minimum width or decimal precision dynamically at runtime from a usize variable using the $ suffix:
fn main() {
let value = std::f64::consts::PI;
for (width, prec) in [(8, 2), (10, 4), (12, 6)] {
println!("{value:>width$.prec$}");
}
}
3.14
3.1416
3.141593
Escaping Literal Braces ({{ and }})
To output a literal { or } inside a format string, double the brace ("{{" produces "{", and "}}" produces "}").