Sub topic 2
Format strings and placeholders
This chapter explains what happens between the opening quote of println!("...") and the text that appears on screen. It assumes you can write and run a basic Rust program with cargo run. It also assumes you know what a trait is, but not how to implement one. Later chapters cover the details of Display, Debug, and the layout options. Here you learn the parts that all of them share.
What a format string is
A format string is the first argument of println! and its relatives. It is ordinary text with placeholders. A placeholder is a pair of braces, {}, that marks where a value goes. Everything outside the braces is copied to the output unchanged.
fn main() {
let item = "tea";
let count = 3;
println!("{} cups of {}", count, item);
println!("{:?} and {}", item, item);
}This prints:
3 cups of tea
"tea" and teaThe first line fills the two placeholders from left to right. The second line uses {:?} for the first value. The text after the colon selects a different formatting trait, so the quotes appear.
Anatomy of a placeholder
Every placeholder has the same shape. Each part is optional.
{ argument : specification }| Part | Example | Meaning |
|---|---|---|
| Argument | `{0}`, `{name}` | Which value to print. If left out, the next unused value is taken in order. |
| Colon | `{:?}` | Separates the argument from the specification. Omit it when there is no specification. |
| Specification | `{:>8.2}` | Fill, alignment, sign, width, precision, and the type character. |
Later chapters cover argument forms and the layout options in detail. For now, remember that the part before the colon chooses the value, and the part after it chooses how to print that value.
The type character picks the trait
The last item in the specification is the type character. It decides which formatting trait Rust calls to turn the value into text. An empty type character means Display.
| Placeholder | Trait | Typical use |
|---|---|---|
| `{}` | `Display` | Text for users |
| `{:?}` | `Debug` | Text for programmers |
| `{:x}` / `{:X}` | `LowerHex` / `UpperHex` | Hexadecimal |
| `{:o}` | `Octal` | Octal |
| `{:b}` | `Binary` | Binary |
| `{:e}` / `{:E}` | `LowerExp` / `UpperExp` | Scientific notation |
| `{:p}` | `Pointer` | Memory address |
The choice of trait changes the output, even for simple values:
fn main() {
println!("{} {:x} {:b}", 255, 255, 5);
println!("{} {:?}", 2.0, 2.0);
println!("{} {:?}", "hi", "hi");
}This prints:
255 ff 101
2 2.0
hi "hi"Display for a float drops a trailing .0, while Debug keeps it. Debug for a string keeps the quotes, so you can see where the string starts and ends.
A type can implement Display but not Debug, or the reverse. The compiler checks the trait that the placeholder names, and only that one. Because the traits are separate, the language lets library authors give a type a friendly Display form and a precise Debug form.
How the compiler processes the string
Format strings are not processed while the program runs. The macro parses the string during compilation and generates code that calls the right trait method for each placeholder.
This design has two consequences. First, the format string must be a string literal written directly in the macro call. Second, many mistakes become compile errors instead of crashes.
Mistakes the compiler catches
Each row below describes a call that fails to compile and the reason.
| Call | Problem |
|---|---|
| `println!("{} {}", 1)` | Two placeholders, one argument. |
| `println!("{}", 1, 2)` | The second argument is never used. |
| `println!("{}", vec![1, 2])` | `Vec<i32>` does not implement `Display`. |
| `println!("{:x}", 1.5)` | `f64` does not implement `LowerHex`. |
| `println!("{name}")` with no `name` in scope | The name cannot be resolved. |
The third row is the one you will meet most often. It is why {:?} exists: collections have no single obvious user-facing text, but they do have a Debug form. The compiler error names the missing trait, so you can tell whether to switch to {:?} or to implement the trait yourself.
Evaluation and borrowing
The macro takes a reference to each argument. It does not move or copy them. This is why you can print the same String twice and still use it afterwards:
fn main() {
let s = String::from("hi");
println!("{}", s);
println!("{}", s);
let owned = s;
println!("{owned}");
}Each argument expression is evaluated once, from left to right, even if a placeholder refers to it several times. The next program shows this with a counter:
fn main() {
let mut n = 0;
let mut next = || {
n += 1;
n
};
println!("{0} {0} {1}", next(), next());
}This prints 1 1 2. The first call to next() produces 1, and placeholder {0} uses that stored result twice. The second call produces 2. So the expression next() ran twice, not three times.
One syntax, many macros
Placeholders also follow one rule about trait choice. If a macro accepts a format string, the argument types must implement the trait that each placeholder names. Therefore a message in assert!(x > 0, "x was {:?}", x) fails to compile if x has no Debug implementation.
Common errors to recognize
- Treating
{}as a catch-all. It only works for types with aDisplayimplementation, which excludesVec,Option, and most structs. - Counting placeholders wrongly after mixing forms. An empty
{}uses its own counter, which does not advance when you write{0}. The callprintln!("{} {0} {}", "a", "b")printsa a b. - Forgetting that a trailing
{or}is special. A literal brace needs doubling, which a later chapter covers. - Passing unused arguments. Rust rejects them because they usually signal a typo.
Exercise
Which of these calls fail to compile, and why? (1) println!("{} and {}", 1); (2) println!("{0} {0}", 7); (3) let v = vec![1, 2]; println!("{}", v); (4) println!("{:?}", vec![1, 2]);
Show answer
Calls 1 and 3 fail. Call 1 has two placeholders but only one argument. Call 3 uses {} with a Vec, which does not implement Display. Calls 2 and 4 compile: call 2 reuses one argument twice, and call 4 uses Debug, which Vec implements.
Exercise
What does println!("{} {0} {}", "a", "b") print, and why?
Show answer
It prints "a a b". The empty placeholders take arguments in order using their own counter, so the first {} gets "a" and the second {} gets "b". The explicit {0} picks "a" again without moving that counter.