Sub topic 8
Respecting width and precision in Display
This chapter assumes you can write impl fmt::Display for T with write!. It also assumes you know the basic format spec syntax, such as {:>8} and {:.2}. You will learn why those specs are sometimes silently ignored for your own types, and how to honor them.
The spec is data, not behavior
A format spec such as {:>8.2} is not applied by println!. The macro parses it and stores the result in a Formatter. It then calls your fmt method and passes that Formatter. Whatever width, fill, alignment, and precision the caller wrote are available to you as values. Nothing forces your code to use them.
The common mistake: write! ignores the spec
Here is a type whose Display looks correct but does not respect width.
use std::fmt;
struct Plain(&'static str);
impl fmt::Display for Plain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
fn main() {
println!("[{:>8}]", Plain("rust"));
}This prints [rust]. The write! call creates a new, default format for its arguments. The caller's >8 is never consulted. The compiler does not warn about this, because ignoring the spec is legal.
The same applies to to_string(). It builds the string with a default Formatter, so no spec reaches your code at all. If you need padding, apply it in the format string at the call site, or pad the resulting String.
Three ways to honor the spec
1. Use `f.pad` for string-like output
Formatter::pad writes a &str and applies the caller's width, fill, alignment, and precision. For strings, precision means a maximum number of characters, so it truncates.
2. Delegate to the inner value
If your type wraps a value that already implements Display, call that value's fmt and pass the same Formatter. The inner type then applies the spec. Call the trait method by its full path, because self.0.fmt(f) can be ambiguous when both Debug and Display are in scope.
3. Read the settings and apply them yourself
Formatter exposes the spec through accessor methods. Use these when your output has structure that pad would handle badly, such as several numbers in one string.
| Method | Returns | Meaning |
|---|---|---|
| `f.width()` | `Option<usize>` | Minimum width, if given |
| `f.precision()` | `Option<usize>` | Digits after the point for floats, maximum characters for strings |
| `f.fill()` | `char` | Fill character, a space by default |
| `f.align()` | `Option<fmt::Alignment>` | `Left`, `Right`, or `Center`, if given |
| `f.alternate()` | `bool` | `true` when `#` was used |
| `f.sign_plus()` | `bool` | `true` when `+` was used |
All three in one program
This program is complete and runs as shown.
use std::fmt;
struct Plain(&'static str);
struct Padded(&'static str);
struct Meters(f64);
struct Point {
x: f64,
y: f64,
}
impl fmt::Display for Plain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Display for Padded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.0)
}
}
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)?;
f.write_str(" m")
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = match f.precision() {
Some(p) => format!("({:.*}, {:.*})", p, self.x, p, self.y),
None => format!("({}, {})", self.x, self.y),
};
match f.width() {
Some(w) => write!(f, "{:>w$}", text, w = w),
None => write!(f, "{}", text),
}
}
}
fn main() {
println!("[{:>8}]", Plain("rust"));
println!("[{:>8}]", Padded("rust"));
println!("[{:*^8}]", Padded("rust"));
println!("[{:.2}]", Padded("rust"));
println!("[{:8.2}]", Meters(3.14159));
let p = Point { x: 1.0, y: 2.46 };
println!("[{}]", p);
println!("[{:.1}]", p);
println!("[{:14.1}]", p);
}The output is:
[rust]
[ rust]
[**rust**]
[ru]
[ 3.14 m]
[(1, 2.46)]
[(1.0, 2.5)]
[ (1.0, 2.5)]Line by line:
Plainignores>8, so the first line has no padding.Paddedgets right alignment, a custom fill with centering (*^8), and truncation to two characters (.2), all from one call tof.pad.Meterspasses the formatter tof64'sDisplay. The8.2applies to the number only, so the width covers3.14, and the unitmis added afterward. That is usually what you want for a unit suffix, but it means the total width is 10, not 8.Pointreads the precision and uses it for both coordinates with{:.*}, which takes the precision as an argument before the value. It reads the width and applies it to the whole text.
Gotchas and edge cases
Precision truncates under `pad`
If Point called f.pad(&text) instead of handling width manually, then {:.1} would cut the text to one character and print [(]. For composite output, either read precision() yourself, as Point does, or do not support it.
Hardcoded alignment
Point always right-aligns. A fuller version would read f.align() and f.fill(). If you want full fidelity for a single string, build the text and use pad, and accept that precision truncates. Pick one policy and document it.
Delegation applies the spec to every inner call
If you delegate for several fields, each field receives the full spec. With {:6.1}, a type that delegated for both x and y would pad each coordinate to six characters, not the whole value. The standard library does this too. A derived Debug passes the formatter to its fields, so format!("{:5?}", Some(1)) gives Some( 1). This is correct behavior, but it surprises people.
Do not call `write!(f, "{:>8}", ...)` and also expect the caller's spec
A literal spec inside write! always wins over the caller's spec for that argument. Use it only when your type's layout is fixed on purpose, such as a table cell that must always be 8 wide.
Choosing an approach
| Your type | Approach | Spec behavior |
|---|---|---|
| Wraps a string or is label-like | `f.pad(text)` | Width, fill, alignment, and truncating precision all work |
| Wraps one number | `fmt::Display::fmt(&self.0, f)` | Everything the inner number supports works |
| Number plus a unit | Delegate, then `f.write_str(unit)` | Spec applies to the number only |
| Several values in one string | Read `f.precision()` and `f.width()` | You decide what each setting means |
| Layout is fixed | `write!` with literal specs | Caller's spec is ignored on purpose |
Exercise
Given struct Tag(&'static str); with impl Display that calls write!(f, "{}", self.0), what does println!("[{:<6}]", Tag("ab")) print? What single change to the fmt body makes it print [ab ], and what does println!("[{:.1}]", Tag("ab")) print after that change?
Show answer
The first version prints [ab], because write! creates a fresh default format and the caller's width is never used. Replacing the body with f.pad(self.0) makes it print [ab ], since <6 left-aligns and pads to width 6. With pad, {:.1} is a maximum character count, so it prints [a].
Exercise
A type Percent(f64) should print 12.50% for format!("{:.2}", Percent(12.5)), and {:8.2} should pad only the number. Write the body of its fmt method.
Show answer
fmt::Display::fmt(&self.0, f)?; f.write_str("%"). Delegating passes the caller's precision and width to f64, so {:.2} gives 12.50 and {:8.2} gives 12.50. The % is appended afterward and is not padded.