Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ THE FIRST BUILD
BUILD NOTE 04 / 53

Make the output tell a story.

Use formatting traits to create readable messages and diagnostic output.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/formatting/src/main.rs
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);
}
↳ EXPECTED OUTPUT
elapsed=12.35ms
samples=[3, 5, 8]
    Rust | 007
  1. 1

    Precision rounds the formatted float, not the stored variable.

  2. 2

    Arrays support Debug output.

  3. 3

    Width and zero-padding are presentation choices.

From the extracted rust-workbench folder
cargo run -p lesson_formatting

03 Mind the boundary

04 Your next build

A SMALL MISSION

Print a price with two decimal places and an ID padded to four digits.

Reveal one possible solution +
solutions/formatting/src/main.rs
fn main() {
    assert_eq!(format!("{:.2}", 9.5), "9.50");
    assert_eq!(format!("{:04}", 23), "0023");
}

05 Check your reasoning

QUICK SIGNAL CHECK

What does {:?} request?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.