Formatting
Use format!, write!, and std::fmt traits with precision, width, alignment, and custom Display/Debug.
Busca en todas las páginas de la documentación
Use format!, write!, and std::fmt traits with precision, width, alignment, and custom Display/Debug.
fn main() {
let pi = 3.14159;
println!("{pi:.2}");
let s = format!("{:>8}", "right");
println!("{s}");
}When to reach for this: User-facing strings, logs, tables, padded output.
use std::fmt;
struct Percent(f64);
impl fmt::Display for Percent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.1}%", self.0 * 100.0)
}
}
fn main() {
println!("{}", Percent(0.856));
}What this demonstrates:
Display for domain formattingwrite! macro inside implSpecifiers: hex, binary, {:?} Debug, {:#?} pretty Debug, {name} named args, {:08} pad zeros.
Display.write!.| Alternative | Use When | Don't Use When |
|---|---|---|
itertools::format | Join iter | Simple format! |
| templating crates | HTML/email | Small CLI message |
serde_json::to_string | JSON not human | User text |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026