Sub topic 15
Respecting width and alignment with Formatter::pad
This chapter assumes you can write impl fmt::Display for a type and know that {:>8} sets width and alignment. If not, review the chapters on width and on implementing Display first.
The problem: width is ignored by default
A format specifier such as {:>6} does not act on your value directly. Rust stores the width, fill, alignment, and precision in the Formatter passed to your fmt method. Your code decides whether to honor them.
When you call write!(f, "tag"), you create a fresh set of format arguments with default options. The caller's width is dropped. The output is correct but ignores the layout the caller asked for.
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);
println!("[{:<6}]", Padded);
println!("[{:*^7}]", Padded);
println!("[{:.2}]", Padded);
}This prints:
[tag]
[ tag]
[tag ]
[**tag**]
[ta]The first line shows the problem. Plain ignores {:>6}. The other lines show Padded respecting each option.
What pad does
Formatter::pad(&mut self, s: &str) writes a string slice while applying the options held by the formatter:
- Width: pads the text up to the minimum width.
- Fill and alignment: uses the fill character and the
<,^, or>flag. With no flag, text is left-aligned. - Precision: truncates the text to at most that many characters. This is why
{:.2}producedta.
Width counts characters, not bytes, so pad handles non-ASCII text without splitting a character.
Delegating to an inner value
If your type wraps a string, you can pass the call on and keep all options. Calling Display::fmt on the inner value reuses the same formatter.
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() {
let n = Name("Ferris".to_string());
println!("[{:>8}]", n);
println!("[{:-<8}]", n);
}This prints [ Ferris] and [Ferris--]. For a type that builds its text on the fly, such as a String assembled from several fields, use f.pad(&text) instead.
When to use pad
Use pad when your type prints as one unit of text, such as a tag, a name, or a status label. Callers often put these in aligned tables, so ignoring width would break their columns.
Do not use pad for a multi-part value like (1, 2). Applying width to the whole string would be ambiguous: it could apply to the whole value or to each number. Standard types make a choice for their own case, and for your own type plain write! is usually fine.
Exercise
A type implements Display with write!(f, "ok"). What does println!("[{:>5}]", value) print, and what single change to the fmt body makes it print [ ok]?
Show answer
It prints [ok], because write! builds new arguments with default options and drops the caller's width. Replacing the body with f.pad("ok") makes it print [ ok].