Skip to content
Formatting
step 1/5

Reading — step 1 of 5

Learn

~3 min readStrings

Formatting

Rust's formatting machinery has one deeply pleasant property: it's checked at compile time. A wrong placeholder count isn't mangled output at 2 a.m. — it's a build failure at 2 p.m. This lesson makes you fluent in the {} mini-language, because byte-exact output is how every exercise here is graded.

The core

let name = "Alice";
let age = 30;

println!("Hi, {}. You're {}.", name, age);      // positional, in order
println!("{0} and {1} and {0} again", "a", "b"); // by index
println!("{name} is {age}");                     // captured from scope (modern Rust)

That third form — variables named inside the braces — is current idiom and reads best; use it whenever you're printing variables directly.

{} uses the type's Display — its "for humans" rendering. Numbers, strings, chars all have one. Vectors and other data structures deliberately don't — for them you use Debug formatting:

let nums = vec![1, 2, 3];
println!("{:?}", nums);      // [1, 2, 3]        — Debug: "for programmers"
println!("{:#?}", nums);     // pretty, multi-line — the debugging workhorse

{:?} works on almost everything (your own structs join in with one line, #[derive(Debug)], in chapter 5). When you just need to see a value mid-debug, {:?} is the answer; dbg!(expr) goes one better — it prints the file, line, expression text, and value, and hands the value back so you can wrap it around anything inline.

Precision, width, padding

The format spec goes after a colon:

let pi = 3.14159265;
println!("{:.2}", pi);       // 3.14     — two decimals (rounds, not truncates)
println!("{:8.2}", pi);      //     3.14 — width 8, right-aligned
println!("{:<8.2}|", pi);    // 3.14    | — left-aligned
println!("{:08.2}", pi);     // 00003.14 — zero-padded
println!("{:>6}", 42);       //     42   — width 6 for integers too
println!("{:04}", 7);        // 0007

{:.2} is the one to burn in: "two decimal places" appears in graded output formats constantly, and it rounds (3.146 → 3.15). Alignment (< left, > right, ^ center) plus width covers every table you'll ever print.

The whole family, one syntax

Learn the mini-language once, use it in five places:

println!("x = {x}");                  // print + newline
print!("no newline");                 // print, no newline
let s = format!("({x}, {y})");        // build a String — the Sprintf of Rust
eprintln!("error: {e}");              // stderr — keeps stdout clean for graders!
panic!("bad state: {code}");          // even panics format

format! replaces every string-gluing + chain you'd otherwise write, and eprintln! matters more than it looks for this course: test graders read stdout only, so debug prints on stderr (eprintln!) don't break your test output. That trick alone will save you a resubmission or three.

Your exercise: Greeting Card

Fixed text with interpolated values, exact spacing, exact newlines. The reliable method: write the expected output literally in a scratch comment, then transcribe it placeholder by placeholder — each {} replacing exactly one value, each line ending where println! ends it. If the grader disagrees with output that "looks identical," print it with {:?} once: quotes and escapes make invisible whitespace visible, and the diff explains itself.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…