Sub topic 13
Implementing Display for your struct
This chapter assumes you can define a struct, write an impl block, and use #[derive(Debug)]. Here you will give a struct a human-readable text form with the Display trait.
Debug versus Display
Debug is for programmers. You can derive it, and you print it with {:?}. Display is for end users. The compiler cannot guess what a user-facing format should look like, so you cannot derive it. You write it yourself, and you print it with {}.
If you try println!("{}", p) on a struct with no Display implementation, you get error E0277: the struct "doesn't implement std::fmt::Display".
Writing the implementation
Display has one required method, fmt. It receives the value and a Formatter, which is the destination for the output.
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!("{s}");
}The write! macro works like println!, but it writes into the formatter and returns a fmt::Result. Return that value directly, with no trailing semicolon. Adding a semicolon makes the function return (), and the compiler reports a type mismatch.
Every type that implements Display also gets to_string() for free. The standard library provides this through a blanket implementation of ToString. You should not implement ToString yourself.
flowchart LRRespecting width and alignment
Output written with write! ignores format specifiers such as {:>10}. The formatter passes the width to your fmt method, but write! does not apply it. If you want padding to work, build the string first and hand it to Formatter::pad.
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(&format!("({}, {})", self.x, self.y))
}
}
fn main() {
let p = Point { x: 1, y: -2 };
println!("[{:>10}]", p);
println!("[{:<10}]", p);
}This prints the point right-aligned and then left-aligned inside a field 10 characters wide. The cost is one temporary String allocation per call.
Common errors
- Missing import. Write
use std::fmt;or spell outstd::fmt::Display. TheDisplayname is not in the prelude. - Wrong receiver. The method takes
&self. Takingselffails with a signature mismatch. - Display on a field that lacks it. If a field type does not implement
Display,{}on that field will not compile. Print it with{:?}instead, or format its parts yourself. - Calling
println!insidefmt. This writes to stdout and ignores the formatter. Always write tof.
Exercise
Why does println!("[{:>8}]", p) ignore the width when Display::fmt uses write!(f, "({}, {})", self.x, self.y), and how do you fix it?
Show answer
write! writes the pieces straight into the formatter and never applies the width or alignment stored in it. Build the text with format! and pass it to f.pad(&text), which applies the width, alignment, and fill.