Sub topic 18
What the compiler checks in format strings
This chapter assumes you know println!, {} and {:?}, and that a type needs a trait implementation (Display or Debug) before it can be printed.
Checked at compile time
println!, format!, write! and the rest are macros. They read your format string while the program is being compiled, not while it runs. A mistake in the string is therefore a compile error, not a crash.
The compiler checks these things:
| Mistake | What you see |
|---|---|
| Fewer arguments than placeholders | error: 2 positional arguments in format string, but there is 1 argument |
| An argument that no placeholder uses | error: argument never used |
| An inline name such as `{name}` with no variable in scope | error: cannot find value `name` in this scope |
| A format string that is not a literal | error: format argument must be a string literal |
| An unknown format type such as `{:z}` | error: unknown format trait `z` |
| A type without the needed trait | error: `Point` doesn't implement `std::fmt::Display` |
| A width or precision argument that is not a `usize` | error: mismatched types |
The last two rows are type checks. {} requires Display, {:?} requires Debug, and {:x} requires LowerHex. Calling {:x} on a &str fails because strings do not implement that trait.
A literal is required
The format string must be written directly in the macro call. This is not allowed:
fn main() {
let template = "{} items";
// println!(template, 3); // error: format argument must be a string literal
println!("{} items", 3);
println!("{template}: {}", 3);
}The restriction exists so the compiler can see every placeholder. To print a string that is not a literal, pass it as an argument: println!("{}", text).
Fixing the common errors
Each fix is small. This program compiles. The commented lines show the errors it avoids.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
// println!("{}", p); // error: Point doesn't implement Display
println!("{:?}", p);
// println!("{} {}", 1); // error: 2 positional arguments, 1 supplied
println!("{} {}", 1, 2);
// println!("{}", 1, 2); // error: argument never used
println!("{0} {0}", 1);
let width: usize = 6;
println!("[{:>width$}]", p.x + p.y);
}When the error is a missing trait, either switch to {:?} and derive Debug, or implement Display yourself.
What is not checked
The compiler checks the shape of the format string. It does not check whether the output makes sense.
- A precision such as
{:.2}on an integer compiles. The precision is ignored. - A
Displayimplementation can returnErr.println!then panics, andto_string()panics as well. - Output that fails at run time, such as a closed standard output pipe, makes
println!panic. Usewriteln!on a handle if you need to handle that error.
Exercise
The line println!("{} and {}", a); fails to compile. Why does this happen at compile time instead of run time, and what are two ways to fix it?
Show answer
println! is a macro that parses its format string during compilation, so it sees two placeholders but only one argument. You can fix it by passing a second argument, as in println!("{} and {}", a, b);. Alternatively, remove one placeholder, as in println!("{}", a);.