Implement Display for a Rust struct
Implement std::fmt::Display when your type has a deliberate user-facing text representation. Define fmt, write into the supplied Formatter, and return fmt::Result.
pub struct CoordinateLabel {
pub x: i32,
pub y: i32,
}
impl fmt::Display for CoordinateLabel {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "({}, {})", self.x, self.y)
}
}After that implementation, the type works with {} formatting and also gets .to_string() through Rust’s blanket ToString implementation.
The Display method signature
Section titled “The Display method signature”A Display implementation has one required method:
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::ResultThe Formatter is the destination supplied by Rust’s formatting machinery. Write the representation into it rather than constructing a separate String first.
The checked example uses write! because that macro can write formatted text directly into the formatter and return the appropriate formatting result.
Display cannot be derived by the standard library
Section titled “Display cannot be derived by the standard library”Rust can derive Debug, because a programmer-facing structural representation has a reasonable default. Display is different: it represents a deliberate user-facing form, and the standard library cannot decide automatically what that form should be for an arbitrary struct.
Choose what the value should mean as text, then encode that decision in the Display implementation.
Do not implement ToString directly
Section titled “Do not implement ToString directly”Implement Display, not ToString. The standard library provides ToString automatically for types that implement Display.
That means one implementation supports both forms:
format!("{value}");value.to_string();Display and Debug can coexist
Section titled “Display and Debug can coexist”A type can implement both traits. Use Display for the representation you intentionally expose to users and Debug for programmer-facing inspection.
For that choice in detail, see Debug vs Display. If the compiler reports E0277 because {} cannot format your type, see type doesn’t implement Display. For the mapping from format syntax to traits such as Display, Debug, LowerHex, and Binary, see Rust formatting traits.