Sub topic 6
Display: printing values for users
This chapter assumes you know how impl Trait for Type works, how println! format strings behave, and how Result is used. It builds on the previous chapter, where Debug gave you developer-facing output.
What Display is for
std::fmt::Display is the trait behind the {} placeholder. Where Debug shows a value's internal shape for programmers, Display produces the text a person using your program should read. A Point might debug-print as Point { x: 1, y: 2 } but display as (1, 2).
The trait has one required method:
pub trait Display {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
}Debug has the same signature. The two traits are separate, so a type can implement either, both, or neither.
There is no derive for Display
You can write #[derive(Debug)], but #[derive(Display)] does not exist in the standard library. The compiler cannot guess how a user should see your type. Should a Point show as (1, 2), x=1 y=2, or 1,2? That is a design decision, so you write it yourself.
The most common error is printing a type with {} when only Debug is implemented. The compiler reports that the type "doesn't implement std::fmt::Display". The fix is to implement Display, or to use {:?} if developer output is acceptable.
Implementing Display with write!
The Formatter argument is the destination for your output. The write! macro works like println!, but it writes into the formatter and returns a fmt::Result.
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{}", p);
println!("point is {p}");
}Both lines print the same (1, 2) text. The body of fmt is a single write! expression with no semicolon, so its Result is the return value.
<br>
Writing several pieces and using ?
A fmt method often writes several fragments. Each write! returns a fmt::Result, so you propagate failures with ? and finish with Ok(()).
use std::fmt;
struct Tags(Vec<String>);
impl fmt::Display for Tags {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, tag) in self.0.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", tag)?;
}
Ok(())
}
}
fn main() {
let t = Tags(vec!["rust".to_string(), "traits".to_string()]);
println!("{}", t);
}This prints rust, traits. If you forget a ? on a non-final write!, the compiler warns about an unused Result, and a failure from that call would be silently dropped.
A fmt::Error is not a place to report your own problems. It means the underlying output failed, for example a writer that refused data. Do not return Err(fmt::Error) because your value is "invalid". The standard to_string() method panics if fmt returns an error unexpectedly.
Enums: match and write_str
For enums, match on self and emit one string per variant. When you only have a fixed &str and no placeholders, f.write_str is simpler than write!.
use std::fmt;
enum Level {
Low,
High,
Custom(u8),
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Level::Low => f.write_str("low"),
Level::High => f.write_str("high"),
Level::Custom(n) => write!(f, "custom({})", n),
}
}
}
fn main() {
for level in [Level::Low, Level::High, Level::Custom(7)] {
println!("level: {}", level);
}
}Every arm returns a fmt::Result, so the match as a whole is the function's result.
Delegating to an inner Display
If your type wraps a value that already implements Display, you can pass the same formatter straight through. The formatter carries options such as precision, so the inner value honors them.
use std::fmt;
struct Meters(f64);
impl fmt::Display for Meters {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)?;
f.write_str(" m")
}
}
fn main() {
let d = Meters(3.14159);
println!("{}", d);
println!("{:.1}", d);
}The output is 3.14159 m and then 3.1 m. Calling fmt::Display::fmt by its full path avoids ambiguity when a type also implements Debug, because both traits have a method named fmt.
Compare this with write!(f, "{} m", self.0). That form creates a fresh format specification, so a caller's {:.1} would not reach the inner number. Whether to forward options is a design choice. Formatter options get their own treatment later in this tutorial.
Display and the other traits
Display and Debug are meant to coexist. A common arrangement is #[derive(Debug)] for logs and tests, plus a hand-written Display for messages shown to users.
| Aspect | Debug | Display |
|---|---|---|
| Placeholder | `{:?}`, `{:#?}` | `{}` |
| Audience | Developers | End users |
| Derivable | Yes | No |
| Output stability | May change between versions | Part of your type's interface |
| Implemented by most std types | Almost all | Only types with an obvious text form |
Notably, Vec<T>, Option<T>, and () do not implement Display. The standard library avoids guessing a text format for collections, which is why the Tags wrapper above needed a hand-written loop.
Because of Rust's orphan rule, you can implement Display only for types defined in your own crate. You cannot implement it for Vec<String> directly. The usual workaround is a newtype wrapper, as Tags does.
<br>
<br>
Common mistakes
- Using
println!insidefmt. This prints directly to stdout and bypasses the formatter. The value then cannot be written to aString, a file, or a log. Usewrite!(f, ...). - Adding a trailing newline in
fmt. The caller decides where lines end, so useprintln!for that, not\nin the implementation. - Putting a semicolon after the final
write!. The function then returns()instead offmt::Result, and compilation fails. - Calling
{}on a value inside its ownDisplayimplementation, for examplewrite!(f, "{}", self). This recurses forever and overflows the stack. - Expecting
{:>10}to pad your type automatically. Withwrite!, width is ignored unless you forward it, asMetersdoes for precision, or usef.pad.
Exercise
A struct Version { major: u32, minor: u32 } derives only Debug. Calling println!("v{}", version) fails to compile. What is the fix so it prints v2.5 for major 2 and minor 5, and what should the body of fmt be?
Show answer
Implement std::fmt::Display for Version by hand, since Display cannot be derived. The fmt body is write!(f, "{}.{}", self.major, self.minor), written as the final expression with no semicolon so it returns fmt::Result. The original call println!("v{}", version) then prints v2.5. Using {:?} instead would compile, but it would print Version { major: 2, minor: 5 }.
Exercise
Why is println!("{}", value) inside a Display::fmt implementation a bug, even if the output looks right when you test it with println!("{}", x)?
Show answer
println! writes directly to standard output and ignores the Formatter that was passed in. When the value is formatted into a String with to_string() or format!, nothing is captured. The text appears on the terminal at the wrong moment and the string stays empty. The correct approach is to write into the formatter with write!(f, ...) or f.write_str(...).