Sub topic 6
Display: printing values for users
This chapter assumes you know basic Rust syntax, how impl Trait for Type works, and how to use println! format strings. It also assumes you have seen #[derive(Debug)] and {:?}.
Why Display exists
Debug is for developers. Its output is meant for logs and debugging, and derive can write it for you. Display is for the people using your program. Its output is text you choose, such as (1, 2) or port 70000 is out of range.
The compiler cannot guess what a user-facing format should look like, so there is no #[derive(Display)]. You write the implementation yourself. The format string {} calls Display, and {:?} calls Debug.
Implementing Display
Display has one required method, fmt. It receives the value and a Formatter, and it writes text into the formatter. The write! macro does this. It works like println!, except that its first argument is the destination.
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: String = p.to_string();
println!("{}", s);
}This prints (1, 2) twice. The return type fmt::Result is Result<(), fmt::Error>. write! already returns that type, so you can return its result directly.
to_string() for free
The example calls p.to_string(), but Point never defines it. The standard library has a blanket implementation: every type that implements Display also implements ToString. So you implement Display and get to_string() at no cost.
Do not implement ToString yourself. Doing so is almost always a mistake, because it bypasses Display and the two can disagree.
Common errors
- Using
{}on a type withoutDisplay. The compiler reports that the type "doesn't implementstd::fmt::Display". Either implement it or print with{:?}ifDebugis enough. - Forgetting
use std::fmt;. Without it,fmt::Displayandfmt::Formatterare not in scope. - Calling
println!insidefmt. This prints straight to stdout and ignores the formatter. Always write tof. - Ending the method with a semicolon.
write!(...);returns()instead offmt::Result. Leave off the semicolon.
Display versus Debug
| Trait | Format | Audience | Can be derived |
|---|---|---|---|
| `Debug` | `{:?}`, `{:#?}` | Developers | Yes |
| `Display` | `{}` | End users | No |
Exercise
You implement fmt::Display for a struct Temperature(f64). A colleague then writes let t = Temperature(21.5).to_string(); and asks where you defined to_string. What is your answer?
Show answer
You did not define it. The standard library implements ToString for every type that implements Display, so to_string() is available automatically and returns the same text that {} prints.
Exercise
This Display implementation fails to compile. Why? fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0); }
Show answer
The trailing semicolon makes the body evaluate to (), but the function must return fmt::Result. Remove the semicolon so the result of write! is returned.