Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Display trait

Reference for the Rust Display trait: implement fmt for {} output, honor width and precision with pad, get to_string for free, and avoid common mistakes.

std::fmt::Display defines how a value looks to a person. It powers {} in println! and format!, and it gives you ToString for free. Unlike Debug, Display can never be derived: you decide what the text is.

Types such as integers, floats, char, str and String implement it. Vec<T> and Option<T> do not, because there is no single obvious way to show them.

Rust
impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

Try it

Rust Implementing Display

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Honoring width with pad

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub trait Display {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
Name Description
&self The value to show.
f The output sink plus the requested options: f.width(), f.precision(), f.fill(), f.align(), f.alternate(), f.sign_plus().

Returns: fmt::Result. Propagate errors from write! and f.pad as the return value.

Usage notes

  • write!(f, ...) ignores width and alignment that the caller asked for, because you formatted the pieces yourself. Use f.pad(text) for text-like types, or forward to an inner value with fmt::Display::fmt(&self.0, f) to pass every option along.
  • You get to_string() for free. impl<T: Display + ?Sized> ToString for T exists in the standard library. Never implement ToString directly.
  • No derive. For an enum, match self and write one word per variant. A match makes sure new variants are not forgotten.
  • Do not allocate inside fmt if you can write pieces straight to f. Building a String first and then writing it works but wastes memory.
  • Errors are not formatting errors. fmt::Error signals that the sink failed (for example a closed pipe), not that your data is bad. Do not return it for invalid values; a panic inside fmt also aborts the whole println!.
  • User text vs. diagnostics. Implement Display for text shown to end users and error messages (std::error::Error requires Display). Keep Debug for developers.
  • Orphan rule: you can implement Display for your own types, not for Vec<MyType> or Option<T>. Wrap them in a newtype instead.