Sub topic 2
Format strings and placeholders
This chapter assumes you can write a basic Rust main function, declare variables, and run a program with cargo run. It also assumes you know that a trait is a set of behavior a type can implement.
What a format string is
Every macro in the println! family takes a format string as its first argument. It is a string literal that mixes plain text with placeholders. A placeholder is a pair of braces, {}, and the macro replaces it with one of the remaining arguments.
fn main() {
let name = "Ferris";
let age = 7;
println!("Hello, {}!", name);
println!("{} is {} years old", name, age);
println!("{:?}", name);
}This prints:
Hello, Ferris!
Ferris is 7 years old
"Ferris"Placeholders are filled from left to right. The first {} takes the first argument, the second takes the second, and so on.
The shape of a placeholder
A placeholder has two optional parts, separated by a colon: {argument:spec}. The argument part picks which value to print. The spec part says how to print it. {} leaves both empty, so it uses the next argument and the default style.
The spec ends with a type, which is the trait used to format the value. The following chapters cover the other parts in detail.
| Placeholder | Trait used | Typical use |
|---|---|---|
| `{}` | `Display` | Output meant for users |
| `{:?}` | `Debug` | Output meant for programmers |
| `{:#?}` | `Debug`, pretty-printed | Nested values on several lines |
| `{:x}` | `LowerHex` | Hexadecimal numbers |
| `{:b}` | `Binary` | Binary numbers |
The type character selects a trait. If the value's type does not implement that trait, the program does not compile. A Vec<i32> has no Display implementation, so println!("{}", vec![1, 2]) is an error. println!("{:?}", vec![1, 2]) works.
What happens at compile time
The macro reads the format string while the compiler builds your program. It does not read it while the program runs.
Because of this, the compiler catches several mistakes before the program runs:
- A placeholder with no matching argument.
- An argument that no placeholder uses.
- A value whose type lacks the trait the placeholder asks for.
Display and Debug are separate
Most types you meet while learning, such as integers, floats, &str, and String, implement both Display and Debug. For a plain number the output is the same. For strings it differs: {} prints Ferris, while {:?} prints "Ferris" with the quotes. Compound types such as Vec and Option implement only Debug, so they need {:?}.
Exercise
A program contains let v = vec![1, 2, 3]; println!("{}", v);. It fails to compile. What is the cause, and what is the smallest change that fixes it?
Show answer
Vec<i32> does not implement Display, and {} asks for Display. Changing the placeholder to {:?} uses the Debug implementation, which Vec does have, and prints [1, 2, 3].