Sub topic 18
What the compiler checks in format strings
This chapter assumes you can write basic Rust, have used println! with {} and {:?}, and know that Display and Debug are traits. It explains which mistakes in a format string the compiler rejects and which ones it cannot catch.
Why the format string must be a literal
The first argument of println!, format!, write! and the related macros must be a string literal. It cannot be a variable, a const, or the result of a function call.
fn main() {
let name = "Ferris";
println!("Hello, {name}!");
}The reason is that these macros expand to an internal macro called format_args!. The compiler reads the literal while it compiles, splits it into plain text pieces and placeholders, and matches each placeholder to an argument. The compiled program does not parse the string again at run time. This is why a mistake in a format string is a compile error and not a surprise in production.
Macros that expand to a literal are accepted, because the compiler sees the literal after expansion. concat! and stringify! are examples. A const FMT: &str = "{}" is not accepted, because the compiler does not treat a constant's name as a literal.
fn main() {
println!(concat!("id: ", "{}"), 7);
}The checks, in order
The compiler works through these steps for every format macro call.
1. Syntax of the string
An unmatched brace is an error. A lone { or } must be doubled, as you saw in the chapter on literal braces. An unknown format type, such as {:q}, is also rejected, and so is a malformed spec such as {:>>>}.
2. Placeholders versus arguments
The number of placeholders that take positional arguments must match the number of arguments supplied.
| Code | Compiler result |
|---|---|
| `println!("{} {}", 1)` | Error: two positional arguments in the string, one given |
| `println!("{}", 1, 2)` | Error: argument never used |
| `println!("{x}", y = 1)` | Error: no value named `x` is in scope, and `y` is never used |
| `println!("{2}", 1, 2)` | Error: invalid reference to positional argument 2 |
Extra arguments are errors, not warnings. This catches the common case where you edit a format string and forget to remove the old argument.
3. Inline captures
{name} without a matching named argument makes the compiler look for a variable called name in scope. If it does not exist, you get an ordinary "cannot find value" error. Only plain identifiers can be captured. Expressions such as {a + b} or {self.x} are not allowed, so pass them as arguments instead.
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let (a, b) = (3, 4);
println!("{} {} {}", p.x, p.y, a + b);
println!("{a} {b}");
}4. Width and precision arguments
When you write {:width$} or {:.prec$}, the referenced value must be a usize. A variable inferred as i32 produces a type mismatch error. An integer literal such as 10 is inferred as usize when it is used this way.
The .* form takes two arguments from the positional list. The first is the precision and the second is the value. This changes how the implicit counter advances, so mixing .* with other {} placeholders is a frequent source of "argument never used" errors.
fn main() {
let pi = 3.14159_f64;
let width = 8;
let prec = 2;
println!("[{:.*}]", 3, pi);
println!("[{pi:width$.prec$}]");
println!("[{:>1$}]", "x", 4);
}An argument that is used only as a width or precision counts as used, so println!("{:>1$}", "x", 4) compiles.
5. Trait bounds
Each placeholder's format type selects a trait, and the argument must implement it.
| Placeholder | Trait required |
|---|---|
| `{}` | `Display` |
| `{:?}` and `{:#?}` | `Debug` |
| `{:x}` | `LowerHex` |
| `{:X}` | `UpperHex` |
| `{:b}` | `Binary` |
| `{:o}` | `Octal` |
| `{:e}` | `LowerExp` |
| `{:E}` | `UpperExp` |
| `{:p}` | `Pointer` |
If the trait is missing, you get a trait bound error (E0277) that points at the argument.
error[E0277]: `Point` doesn't implement `std::fmt::Display`
= help: the trait `std::fmt::Display` is not implemented for `Point`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) insteadThe fix is one of three things: derive or implement Debug and switch to {:?}, implement Display, or print a field that already has the trait. The same applies to {:x} on a f64 or {:e} on a String. Those types do not implement LowerHex or LowerExp.
References are fine. Display and the other traits are implemented for &T whenever T implements them, so println!("{}", &x) works. The macros also take their arguments by reference, so printing a value does not move it.
Valid but ignored options
Some options are accepted by the compiler but have no effect on certain types. These are not errors, and the compiler does not warn about them.
- A precision on an integer is ignored, so
{:.2}on5prints5. - On a string, a precision truncates it.
{:.2}on"hello"printshe. - A
+flag on a string has no effect.
The compiler checks that the spec is well formed and that the trait exists. Whether a particular type's implementation honors each option is up to that implementation, as you saw with Formatter::pad.
What is only checked at run time
A compile-time check cannot see inside a Display implementation. Two situations fail while the program runs.
use std::fmt;
struct Broken;
impl fmt::Display for Broken {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
Err(fmt::Error)
}
}
fn main() {
let r = std::panic::catch_unwind(|| {
let _ = format!("{}", Broken);
});
println!("panicked: {}", r.is_err());
}This program compiles, then format! panics because the implementation returned Err. The default panic message is also printed to standard error before the program prints panicked: true.
A correct Display implementation should return an error only when the underlying writer returns one. Use ? on write! calls and do not invent errors of your own.
Reading compiler messages
Format errors usually point at the exact piece of the string that is wrong, with a caret under it. Work from the first error down, because one wrong placeholder often causes a second error about an unused argument. When the message mentions "positional arguments", count the {} pairs and remember that .* counts as two.
Exercise
Which of these lines fail to compile, and why? (a) println!("{} {}", 1); (b) println!("{:>1$}", "x", 4); (c) let w: i32 = 5; println!("{:w$}", 1); (d) println!("{a + 1}");
Show answer
(a) fails: two positional placeholders but one argument. (b) compiles: argument 1 is used as the width, so both arguments are used. (c) fails: a width taken through w$ must be a usize, and w is an i32. (d) fails: inline captures accept only plain identifiers, not expressions such as a + 1.
Exercise
A type derives Debug but not Display. You write println!("{}", value);. What happens, and what are two ways to fix it?
Show answer
It fails to compile with a trait bound error because Display is not implemented. Either change the placeholder to {:?} (or {:#?}), or implement fmt::Display for the type.