Implement the Display trait for complex types by defining a fmt method that uses write! to format the output.
Implement the Display trait for your custom type by defining an impl block that implements std::fmt::Display and provides a fmt method using write!.
use std::fmt;
struct Pair<T> {
x: T,
y: T,
}
impl<T: fmt::Display> fmt::Display for Pair<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
The Display trait tells Rust how to turn your custom data structure into a readable string for printing. It matters because without it, you cannot use your type in print statements or format strings. Think of it as defining the specific label or name tag that your object wears when introduced to the outside world.