skip to content

A Rust `Money` type implements `Display` with `write!`, yet `format!("{:>14}", price)` prints no padding — why, and how do you fix the impl?

level: seniorimportance: should knowfreq 35%

answer

  1. the options live in the Formatter
  2. write! starts fresh format arguments
  3. Formatter::pad applies the flags
  4. forward to the inner Display

basics

~20 s

Width, fill and alignment are carried by the Formatter, and a write! inside fmt formats fresh arguments that ignore them. Build the text and call f.pad(&text), or forward the Formatter to an inner value's Display::fmt.

solid answer

~40 s

`{:>14}` stores width 14 and right alignment in the `fmt::Formatter` passed to `Display::fmt`, but honouring them is the impl's job. `write!(f, "{}.{:02} {}", ...)` formats new arguments with their own empty specs, so the outer width is silently ignored; the std docs say each implementation must adhere to the requested parameters itself. The usual fix is to build the text and call `f.pad(&text)`, which applies width, fill and alignment — and treats precision as truncation, so `{:.5}` cuts `19.99 EUR` to `19.99`. A newtype can instead forward with `fmt::Display::fmt(&self.0, f)`, and a type with numeric semantics can read `f.width()` and `f.precision()` or use `pad_integral`.

code

rust · 32 lines
rust
use std::fmt;

struct Money {
    cents: i64,
    currency: &'static str,
}

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sign = if self.cents < 0 { "-" } else { "" };
        let abs = self.cents.unsigned_abs();
        let text = format!("{sign}{}.{:02} {}", abs / 100, abs % 100, self.currency);
        f.pad(&text) // applies the caller's width, fill, alignment and precision
    }
}

struct Label(String);

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f) // hand the same Formatter to String
    }
}

fn main() {
    let price = Money { cents: 1999, currency: "EUR" };
    println!("[{price:>14}]");
    println!("[{price:-<14}]");
    println!("[{price:.5}]"); // pad treats precision as a maximum length
    let label = Label("total".to_string());
    println!("[{label:>8}]");
}

go deeper

for a junior

Recall that a custom Display does not get padding for free; the Formatter carries width and alignment, and the impl must apply them.

for a middle

Explain why write! inside fmt ignores the outer spec, and how Formatter::pad or forwarding to an inner Display::fmt fixes it.

for a senior

Diagnose ragged report columns to an impl that ignores the Formatter, choose between pad, forwarding and reading f.width() and f.precision(), and decide deliberately what precision means for the type.

for a principal

Make honouring width and precision part of the review checklist for public Display impls, with a formatting test, since the failure is silent and type-checks.

## The symptom A report prints amounts in a right-aligned column with `println!("{price:>14}")`. `Money` has a perfectly good `Display` impl written with `write!`, yet the column comes out ragged: every amount starts at the left edge, as if `>14` were not there. Nothing fails to compile, nothing panics. The code is correct by the type checker and wrong on screen. ## Why `write!` drops the caller's width When `format!` reaches the placeholder `{price:>14}`, it builds a `fmt::Formatter` carrying the **options** from that spec — width 14, right alignment, fill `' '` — and calls `Display::fmt(&price, f)`. What happens next is entirely up to the impl: - `write!(f, "{}.{:02} {}", ...)` creates a **new** set of format arguments, with their own (empty) specs, and calls `Formatter::write_fmt`. Those inner placeholders know nothing about the outer `>14`, so the text is written as-is. - The `std::fmt` module docs say this outright: it is up to each format trait implementation to adhere to the requested formatting parameters, and their own `Vector2D` example notes that its `write!`-based formatting "ignores the various flags provided to format strings". The `Formatter::write_fmt` docs even assert that `format!("{:0>8}", Foo(2))` yields `"Foo 2"`. In short, width, fill, alignment and precision are **requests** stored in the `Formatter`; std types honour them, your type only does if you make it. ## Three ways to honour the request | Technique | How | Honours | Cost / caveat | |---|---|---|---| | `Formatter::pad` | build the text, then `f.pad(&text)` | width, fill, alignment, **precision as truncation** | one temporary `String` | | Forward to an inner value | `fmt::Display::fmt(&self.0, f)` | everything the inner type honours | only when the output *is* one inner value | | Read the options yourself | `f.width()`, `f.precision()`, `f.fill()`, `f.align()` | whatever you implement | the most code | `Formatter::pad` is documented as emitting a string slice "after applying the relevant formatting flags specified": width as a minimum, fill and alignment for the padding, and precision as "the maximum length to emit, the string is truncated if it is longer". It counts **`char`s**, not bytes, so a multibyte currency sign counts as one column. For numeric-looking output, `Formatter::pad_integral` additionally handles the `+` sign flag, the `0` flag and a prefix. ## The `pad` precision surprise Because `pad` treats precision as truncation, `format!("{price:.5}")` on a padded `Money` prints `19.99` — the currency has been cut off. That may or may not be what you want: 1. If precision should mean decimal places for your type, read `f.precision()` and build the number with it before padding. 2. If precision should mean nothing, ignore it: call `pad` only with width-related logic, or document that `.N` truncates. 3. Never leave it undecided — a caller who writes `{:.2}` on money expects a rounding, not a truncated label. ## How `Debug` behaves differently - **Derived `Debug` forwards the same `Formatter` to every field.** So `{:3?}` on `struct Q { a: u8, b: u8 }` pads each field, printing `Q { a: 1, b: 2 }`, and `{:.1?}` on a struct of `f64` fields rounds each one. - **The struct as a whole is not padded.** The std docs warn that alignment "is not generally implemented for the `Debug` trait"; to pad a `Debug` dump, format it into a `String` first and pad that. - Hand-written `Debug` with `write!` has the same blind spot as `Display`. ## Review checklist for a `Display` impl - Does `{:>N}` right-align the whole value? Test it, as the program in this question does. - Does `{:.N}` do something deliberate — round, truncate, or nothing by documented choice? - If the impl wraps one inner value, does it forward with `fmt::Display::fmt(&self.0, f)` instead of `write!(f, "{}", self.0)`? - Does it return only errors the `Formatter` returned, so `to_string()` can never panic? - Is the hot path free of avoidable allocations — for example, writing directly when `f.width()` and `f.precision()` are both `None` and building a padded string only when one is set?

  • Why does `Formatter::pad` turn `{:.5}` on a Money into `19.99`?
    `pad` treats precision as a maximum length in characters and truncates the string before padding. If precision should mean decimal places for your type, read `f.precision()` and use it when building the number, then pad the result.
  • Does a derived `Debug` honour a width such as `{:10?}` in Rust?
    Only per field. The derived impl passes the same `Formatter` to each field, so `{:3?}` pads every field value, while the struct as a whole is not padded. To pad a whole `Debug` dump, format it into a `String` first and pad that.
  • When is forwarding with `fmt::Display::fmt(&self.0, f)` better than `write!(f, "{}", self.0)`?
    Whenever the output is exactly one inner value. Forwarding hands the caller's `Formatter`, with width, fill, alignment and precision, to the inner type's own impl; `write!` with `{}` formats the value with fresh default options and drops them.

  • The formatting macro pads the whole output of any Display impl automatically.
  • write!(f, "{}", self.0) forwards the caller's width to the inner value.
  • Formatter::pad rounds to the requested precision instead of truncating.
  • A width the impl ignores causes a compile error or a runtime panic.
  • Derived Debug pads the whole struct to the requested width.