Sub topic 14
Implementing Display for your own type
This chapter assumes you know what a trait is, how to define a struct and an enum, and how println! placeholders work. Here you will make {} work with your own types.
Why there is no derive
You can write #[derive(Debug)] and get {:?} for free. There is no equivalent for Display. The standard library cannot guess how you want a type shown to users, so you implement std::fmt::Display yourself.
The trait has one required method, fmt. It receives the value and a Formatter, which is the destination for the text.
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.
How the call flows
write! works like println!, but it writes into the Formatter instead of standard output. It returns a fmt::Result, and you return that value as the result of fmt.
You also get to_string
Any type that implements Display automatically gets to_string(). The standard library provides it through the ToString trait. You never implement ToString directly.
Displaying an enum
For an enum, match on the variant and write the text for each one.
use std::fmt;
enum Level {
Info,
Warn,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Level::Info => write!(f, "info"),
Level::Warn => write!(f, "warn"),
}
}
}
fn main() {
println!("level: {}", Level::Warn);
}Common errors
- Missing import. Without
use std::fmt;you must write the full pathstd::fmt::Display. The compiler reports thatfmtis not found. - Using
{}before implementing. The compiler reports that the type "doesn't implementstd::fmt::Display". Implement the trait, or use{:?}with a derivedDebug. - Infinite recursion. Calling
self.to_string()orformat!("{}", self)insidefmtcallsfmtagain and overflows the stack. Write tofdirectly. - Dropping the result. If you end
fmtwith a semicolon afterwrite!, the function returns()and fails to compile. Return thewrite!expression. - Ignoring width.
{:>10}has no effect with a plainwrite!, because your code never reads the caller's options. TheFormatter::padchapter covers the fix.
Exercise
Implement Display for struct Celsius(f64) so that println!("{}", Celsius(21.5)) prints 21.5°C. Which macro do you use inside fmt, and what must fmt return?
Show answer
Use write!(f, "{}°C", self.0) as the last expression of fmt. It returns the fmt::Result that write! produces, so fmt returns that value directly.