Make the output tell a story.
Use formatting traits to create readable messages and diagnostic output.
01 Understand the contract
Formatting uses placeholders rather than concatenating everything manually. Display formatting with {} is intended for human-readable values; Debug formatting with {:?} is intended for inspection. Named arguments make output easier to maintain. You can set width, alignment, and precision without changing the underlying value. Comments explain intent, constraints, and surprising decisions. A comment repeating the next line usually adds less value than a clear variable name.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let elapsed = 12.3456;
let samples = [3, 5, 8];
// Keep report precision stable for readers.
println!("elapsed={elapsed:.2}ms");
println!("samples={samples:?}");
println!("{name:>8} | {count:03}", name = "Rust", count = 7);
}elapsed=12.35ms
samples=[3, 5, 8]
Rust | 007- 1
Precision rounds the formatted float, not the stored variable.
- 2
Arrays support Debug output.
- 3
Width and zero-padding are presentation choices.
cargo run -p lesson_formatting03 Mind the boundary
04 Your next build
Print a price with two decimal places and an ID padded to four digits.
Reveal one possible solution +
fn main() {
assert_eq!(format!("{:.2}", 9.5), "9.50");
assert_eq!(format!("{:04}", 23), "0023");
}05 Check your reasoning
What does {:?} request?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.