Sub topic 13
Implementing Display for Your Struct
This chapter assumes you know how to define a struct, write an impl block, and use &self methods. It also assumes you have seen #[derive(Debug)] and the println! macro. Here you will learn how to give a struct a human-readable text form by implementing the Display trait.
Why Display exists
#[derive(Debug)] gives you a text form for programmers. It is printed with {:?} and its layout is chosen by the compiler. You cannot customize it much, and it often shows internal field names.
Display is the trait for text meant for end users. It is printed with {}. The standard library does not let you derive it, because there is no single correct way to show a struct to a person. You write the implementation yourself.
| Trait | Format specifier | Derivable | Audience |
|---|---|---|---|
| `Debug` | `{:?}` or `{:#?}` | Yes | Developers |
| `Display` | `{}` | No | End users |
The minimal implementation
Display lives in std::fmt. It has one required method, fmt. That method receives &self and a mutable Formatter, and it returns 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);
}This prints (1, -2).
The write! macro works like println!, but it writes into the formatter instead of standard output. It returns a fmt::Result, which is why the method body is a single expression with no semicolon. The Formatter can point at standard output, a String, a file, or any other destination, so your code does not need to know where the text goes.
The parts of the signature are easy to get wrong, so here is what each one means:
impl fmt::Display for Pointmeans you are implementing a trait that is defined elsewhere for your own type. This is allowed becausePointis local to your crate.&selfis a shared borrow. Formatting must not change the value.fmt::Resultis an alias forResult<(), fmt::Error>. It reports whether writing succeeded.
What you get for free: to_string
Once a type implements Display, the standard library gives it to_string() through a blanket implementation of the ToString trait. You should not implement ToString yourself.
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: 3, y: 4 };
let s: String = p.to_string();
println!("Point as text: {s}");
println!("Length: {}", s.len());
}The output is Point as text: (3, 4) followed by Length: 6.
A Display implementation is also what lets your type be used as an error message, since std::error::Error requires Display.
Showing several lines or a list
The fmt method can call write! more than once. Each call appends to the same formatter. Use the ? operator to stop early if any write fails.
use std::fmt;
struct Inventory {
items: Vec<String>,
}
impl fmt::Display for Inventory {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (i, item) in self.items.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", item)?;
}
write!(f, "]")
}
}
fn main() {
let inv = Inventory {
items: vec!["sword".to_string(), "shield".to_string()],
};
println!("{}", inv);
}This prints [sword, shield]. The last write! has no ? and no semicolon, so its result becomes the return value.
Respecting width and alignment flags
Callers can write {:>10} or {:<8} to pad output. A write! call inside fmt ignores those flags, because it writes straight to the formatter. Padding then silently does nothing for your type.
use std::fmt;
struct Tag(String);
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
fn main() {
let t = Tag("rust".to_string());
println!("[{:>10}]", t);
}This prints [#rust], not a right-aligned value. To honor the flags, build the text first and hand it to Formatter::pad, which applies width, alignment, and precision.
use std::fmt;
struct Tag(String);
impl fmt::Display for Tag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let text = format!("#{}", self.0);
f.pad(&text)
}
}
fn main() {
let t = Tag("rust".to_string());
println!("[{:>10}]", t);
println!("[{:<10}]", t);
}The output is [ #rust] and then [#rust ]. Another option is to forward to the inner value, as in fmt::Display::fmt(&self.0, f). That passes every flag to the field's own implementation.
Combining Display with Debug
A struct can implement both traits. Derive Debug for logs and write Display for users. The two outputs do not need to match.
use std::fmt;
#[derive(Debug)]
struct User {
name: String,
age: u32,
}
impl fmt::Display for User {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ({})", self.name, self.age)
}
}
fn main() {
let u = User { name: "Ada".to_string(), age: 36 };
println!("{}", u);
println!("{:?}", u);
}The first line is Ada (36). The second is User { name: "Ada", age: 36 }.
Common errors
- Calling
{}on a type withoutDisplay. The compiler reports that the type "doesn't implementstd::fmt::Display". Either implement it or print with{:?}ifDebugis derived. - Forgetting
use std::fmt;. Without it,fmt::Displayandfmt::Formatterare not in scope. - Adding a semicolon after the last
write!. The method then returns()instead offmt::Result, and the compiler reports a type mismatch. - Calling
println!("{}", self)insidefmt. This recurses forever and overflows the stack. Write to the formatterfinstead. - Implementing
ToStringdirectly. This conflicts with the blanket implementation. ImplementDisplayand callto_string(). - Trying to implement
Displayfor a type you do not own, such asVec<T>. The orphan rule forbids it. Wrap the type in a newtype struct, which a later chapter covers.
How formatting flows
When println! meets {}, it calls your fmt method with a formatter that is bound to its destination.
Exercise
Write a Display implementation for struct Temperature(f64) that prints a value such as 21.5°C with one digit after the decimal point. Then explain why println!("[{:>8}]", t) would not right-align your output if you used write!, and which method fixes it.
Show answer
Use write!(f, "{:.1}°C", self.0) inside fmt. Padding is ignored because write! writes straight to the formatter and does not apply the caller's width or alignment flags. Build the string with format!("{:.1}°C", self.0) and pass it to f.pad(&text), which applies width, alignment, and precision.
Exercise
Why does impl fmt::Display for Vec<i32> fail to compile in your crate, and what is the standard fix?
Show answer
Both the trait Display and the type Vec<i32> are defined outside your crate, so the orphan rule rejects the implementation. The fix is to wrap the vector in a local newtype, such as struct Numbers(Vec<i32>);, and implement Display for that wrapper.