Sub topic 8
Respecting width and precision in Display
This chapter assumes you can write impl fmt::Display for T with write!, and that you know format specs such as {:>8} and {:.2}.
The problem: flags are silently ignored
A format spec like {:>8} is stored in the Formatter that fmt receives. write!(f, "{}", ...) creates a new inner format spec, so the caller's width, fill, alignment, and precision are dropped. The compiler gives no warning.
use std::fmt;
struct PlainTag(String);
struct Tag(String);
impl fmt::Display for PlainTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(&self.0)
}
}
fn main() {
let a = PlainTag("rust".to_string());
let b = Tag("rust".to_string());
println!("[{:>8}]", a);
println!("[{:>8}]", b);
println!("[{:*<8}]", b);
println!("[{:.2}]", b);
}This prints:
[rust]
[ rust]
[rust****]
[ru]Formatter::pad writes a string while applying the caller's width, fill, alignment, and precision. For strings, precision means truncation.
Forwarding to an inner value
If your type wraps a number, pass the same Formatter to the inner type's Display. The inner type then reads the flags itself.
use std::fmt;
struct Meters(f64);
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)?;
write!(f, " m")
}
}
fn main() {
println!("[{:8.2}]", Meters(3.14159));
println!("[{}]", Meters(2.5));
}This prints:
[ 3.14 m]
[2.5 m]The width of 8 applies to the number only. The unit suffix is added afterward. If you want the width to cover the whole text, build a String first and call f.pad(&text).
Reading the options yourself
Formatter also exposes the options directly.
| Method | Returns | Meaning |
|---|---|---|
| `f.width()` | `Option<usize>` | The `8` in `{:8}` |
| `f.precision()` | `Option<usize>` | The `2` in `{:.2}` |
| `f.fill()` | `char` | The fill character, a space by default |
| `f.alternate()` | `bool` | True when `#` is used, as in `{:#}` |
Read them when you need custom behavior, such as printing a different number of decimals based on f.precision().
Common mistakes
- Using
write!(f, "{}", self.0)for a wrapper type and expecting{:>8}to work. - Forwarding to the inner type and then adding extra text, which makes the output wider than the requested width.
- Using
f.write_strand expecting padding.write_strwrites the text as given.
Exercise
A type Id(u32) implements Display with write!(f, "{}", self.0). Why does println!("[{:05}]", Id(42)) print [42] instead of [00042], and how do you fix it?
Show answer
write! builds a fresh format spec, so the caller's zero-padded width of 5 is discarded. Forward the formatter instead with fmt::Display::fmt(&self.0, f), and the inner u32 applies the width and prints [00042].