Sub topic 14
Implementing Display for your own type
This chapter assumes you know how to define structs and enums and what a trait is. You should also know the {} placeholder from earlier chapters. By the end, you will be able to make your own types work with println!, format!, and to_string().
What the trait requires
std::fmt::Display has one required method:
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::ResultThe Formatter is the destination for the text. It also carries the options from the placeholder, such as width and precision. The return type fmt::Result is an alias for Result<(), fmt::Error>. You write text into the formatter and return its result.
Rust has no #[derive(Display)]. The standard library cannot guess how a type should look to an end user, so you write that yourself.
A first implementation
The write! macro works like println!, but its first argument is the destination. Passing the formatter sends the text there.
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}");
let s = p.to_string();
println!("{} has {} characters", s, s.len());
}This prints (1, 2) and then (1, 2) has 6 characters.
write! returns a fmt::Result, and the last expression of fmt is that value, so there is no semicolon. You also get to_string() for free. The standard library has a blanket implementation of ToString for every type that implements Display, so you never implement ToString yourself.
Building on other Display types
Inside fmt, any value that already implements Display can appear in a {} placeholder. This lets you build output from smaller pieces. An enum usually picks its text with match, and a struct can then reuse that enum in its own output:
use std::fmt;
enum Level {
Info,
Warn,
Error,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let text = match self {
Level::Info => "INFO",
Level::Warn => "WARN",
Level::Error => "ERROR",
};
write!(f, "{text}")
}
}
struct Entry {
level: Level,
message: String,
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}] {}", self.level, self.message)
}
}
fn main() {
let e = Entry {
level: Level::Warn,
message: String::from("disk almost full"),
};
println!("{e}");
}The output is [WARN] disk almost full. The call write!(f, "[{}] {}", self.level, self.message) runs Level::fmt with the same formatter, so the pieces end up in one output stream.
Several writes and the `?` operator
A single fmt call may need several write! calls, for example when it loops over a collection. Each call returns a Result, so propagate the error with ? and finish with Ok(()).
use std::fmt;
struct Path(Vec<String>);
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, part) in self.0.iter().enumerate() {
if i > 0 {
write!(f, "/")?;
}
write!(f, "{part}")?;
}
Ok(())
}
}
fn main() {
let p = Path(vec!["usr".to_string(), "local".to_string(), "bin".to_string()]);
println!("{p}");
}This prints usr/local/bin. If you leave out a ?, the compiler warns about an unused Result. The write may have failed, for example when the destination is a closed pipe, and you would be ignoring that failure.
The example also shows the usual way to handle separators. Print the separator before every element except the first.
Why a newtype wrapper?
The Path struct above wraps a Vec<String> instead of implementing Display for the vector directly. Rust's orphan rule allows a trait implementation only if your crate defines either the trait or the type. Display and Vec both come from the standard library, so impl fmt::Display for Vec<String> will not compile. A one-field tuple struct (a newtype) is your own type, so the implementation is allowed.
Forwarding the caller's options
A plain write! ignores the options in the placeholder. {:>10} or {:.2} still reaches your fmt method, but your code never reads them. To honor them, hand the formatter to the inner value's own fmt:
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)?;
write!(f, " m")
}
}
fn main() {
let d = Meters(3.14159);
println!("{}", d);
println!("{:.2}", d);
println!("[{:8.1}]", d);
}The output is:
3.14159 m
3.14 m
[ 3.1 m]The precision and width apply to the number because the formatter carries them into f64's Display. The trailing m is written separately and is not padded. This is a design choice. Decide whether options should apply to the whole output or only to part of it. The next chapter covers Formatter::pad, which pads a whole string.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Using `{}` on a type without `Display` | Compile error: the trait `Display` is not implemented | Implement `Display`, or use `{:?}` if the type derives `Debug` |
| Ending `fmt` with `write!(...);` | Type mismatch: expected `Result`, found `()` | Remove the semicolon |
| Ignoring a `write!` result | Unused `Result` warning | Add `?` |
| Implementing `Display` for `Vec<T>` | Orphan rule error | Wrap the value in a newtype |
| Calling `to_string()` inside your own `fmt` | Works, but allocates a needless `String` | Write directly with `write!` |
Display versus Debug
Use Display for text that end users read. It should be stable and polished. Debug is for programmers, and you can usually derive it. The two traits are independent, so a type may implement one, both, or neither. For types that users see in logs or error messages, implement Display and keep #[derive(Debug)] alongside it.
Exercise
A colleague implements Display for Point with write!(f, "({}, {})", self.x, self.y). They then print println!("[{:>10}]", p) and get [(1, 2)] with no padding. Why, and what is the fix?
Show answer
The formatter receives the width and alignment, but write! writes the text directly and never reads those options, so no padding is added. To honor them, build the text first and call f.pad(&text) on the formatter. The next chapter covers Formatter::pad.
Exercise
Define struct Color(u8, u8, u8) and implement Display so that Color(255, 128, 0) prints as #FF8000. Which write! call does it, and what does {:02X} do?
Show answer
Use write!(f, "#{:02X}{:02X}{:02X}", self.0, self.1, self.2). The X prints a byte in uppercase hexadecimal, 2 sets the minimum width, and the leading 0 pads with zeros, so a value such as 10 prints as 0A instead of A.