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.
impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } }
Try it
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.
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
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. Usef.pad(text)for text-like types, or forward to an inner value withfmt::Display::fmt(&self.0, f)to pass every option along.- You get
to_string()for free.impl<T: Display + ?Sized> ToString for Texists in the standard library. Never implementToStringdirectly. - No derive. For an
enum,match selfand write one word per variant. Amatchmakes sure new variants are not forgotten. - Do not allocate inside
fmtif you can write pieces straight tof. Building aStringfirst and then writing it works but wastes memory. - Errors are not formatting errors.
fmt::Errorsignals that the sink failed (for example a closed pipe), not that your data is bad. Do not return it for invalid values; a panic insidefmtalso aborts the wholeprintln!. - User text vs. diagnostics. Implement
Displayfor text shown to end users and error messages (std::error::ErrorrequiresDisplay). KeepDebugfor developers. - Orphan rule: you can implement
Displayfor your own types, not forVec<MyType>orOption<T>. Wrap them in a newtype instead.
Related
Debug,ToString,fmt::Write,std::error::Error- Lessons: Display and From, Printing