Sub topic 15
Respecting Width and Alignment with Formatter::pad
This chapter assumes you can implement fmt::Display for a struct, as covered in the previous chapter. You should also know the width, fill, alignment and precision specifiers such as {:>8} and {:.2}.
The problem: your Display ignores the caller's options
A format spec like {:>6} does not act on the value directly. The macro builds a Formatter that stores the width, fill, alignment and precision, then passes it to your fmt method. Your method decides whether to honor those options.
A write! call inside fmt does not honor them. It formats its own arguments with a fresh, default spec. The caller's >6 is still stored in f, but nothing reads it.
use std::fmt;
struct Plain;
struct Padded;
impl fmt::Display for Plain {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "tag")
}
}
impl fmt::Display for Padded {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("tag")
}
}
fn main() {
println!("[{:>6}]", Plain);
println!("[{:>6}]", Padded);
}This prints:
[tag]
[ tag]Both types print the same text. Only Padded respects the width.
What Formatter::pad does
Formatter::pad(&mut self, s: &str) -> fmt::Result writes a string slice and applies the stored options the way the built-in str implementation does. It performs these steps in order:
- If a precision is set, it truncates
sto at most that many characters. - If a width is set and the text is shorter, it adds fill characters.
- It places the text according to the alignment.
When the caller gives no alignment, pad aligns left, as strings do. Numbers align right by default, but pad is for text.
use std::fmt;
struct Tag;
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("tag")
}
}
fn main() {
println!("[{:6}]", Tag);
println!("[{:<6}]", Tag);
println!("[{:^6}]", Tag);
println!("[{:*^7}]", Tag);
println!("[{:.2}]", Tag);
}The output is:
[tag ]
[tag ]
[ tag ]
[**tag**]
[ta]Two details are worth noting. With centered alignment and an odd amount of padding, the extra fill character goes on the right, so {:^6} gives one space on the left and two on the right. And {:.2} truncates, because pad treats precision as a maximum length for text, the same as it does for &str.
Reading the options yourself
Formatter exposes the stored options through accessor methods. You can use them when pad does not fit your type.
use std::fmt;
struct Probe;
impl fmt::Display for Probe {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let width = f.width();
let precision = f.precision();
let fill = f.fill();
let align = f.align();
write!(
f,
"width={:?} precision={:?} fill={:?} align={:?}",
width, precision, fill, align
)
}
}
fn main() {
println!("{:*<7.3}", Probe);
}This prints width=Some(7) precision=Some(3) fill='*' align=Some(Left). Unset options come back as None, and fill() defaults to a space. f.alternate() reports whether the # flag was given.
Delegating to an inner value
If your type wraps something that already formats correctly, pass the formatter straight through. The inner fmt then reads the same options, and you don't have to reimplement padding.
use std::fmt;
struct Name(String);
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
fn main() {
println!("[{:>8}]", Name("Ann".to_string()));
}This prints [ Ann]. Delegation also works for numbers. Wrapping an i32 and delegating means {:+05} or {:#x} (with LowerHex) keep working. Numbers are the case where pad alone is wrong, because the standard library formats them with a separate routine that handles sign and 0x prefixes. Delegate to the inner number instead of converting it to a string and padding.
Padding a composite value
A type like Point produces output from several parts, so there is no single inner value to delegate to. A common approach is to build the whole text first and pad it as one unit.
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let text = format!("({}, {})", self.x, self.y);
f.pad(&text)
}
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("[{:>10}]", p);
println!("[{:<10}]", p);
}The output is:
[ (1, 2)]
[(1, 2) ]Trade-offs and gotchas
| Approach | Honors width, fill, align | Honors precision | Cost |
|---|---|---|---|
| `write!(f, ...)` | No | No | None extra |
| `f.pad(s)` | Yes | Yes, as truncation | None if `s` is already a `&str` |
| `f.pad(&format!(...))` | Yes | Yes, as truncation | One `String` allocation per call |
| `Display::fmt(&inner, f)` | Whatever `inner` honors | Whatever `inner` honors | None extra |
Keep these points in mind:
- Precision truncates the whole composite text. With
f.pad(&format!(...)),{:.3}on aPointcuts the output to(1,. That is rarely what you want, so decide whether truncation makes sense for your type. - Width counts characters (Unicode scalar values), not bytes and not screen columns. Wide characters such as many CJK glyphs and emoji take two columns on most terminals, so columns can still look misaligned.
- Derived
Debugon a field-less enum variant writes the variant name without padding, so{:>8?}may not pad it. For table output, implementDisplaywithpadand use{}. - Padding applies once per
fmtcall. If yourfmtcallspadtwice, the width applies to each piece separately.
Exercise
Define enum Level { Info, Warn } and implement fmt::Display so that println!("[{:<6}]", Level::Warn) prints [WARN ] and println!("[{:>6}]", Level::Info) prints [ INFO]. What does your fmt method contain, and why would write!(f, "WARN") fail the requirement?
Show answer
Match on self and call f.pad with the text for each variant: Level::Info => f.pad("INFO") and Level::Warn => f.pad("WARN"). pad reads the width, fill and alignment stored in the Formatter, so <6 pads WARN with two trailing spaces and >6 pads INFO with two leading spaces. write!(f, "WARN") formats its own text with a default spec, so the stored width and alignment are never applied and the output would be [WARN].