Implement the Display trait for your type by defining a fmt method that takes a &self and a &mut Formatter, then use the {} placeholder in format strings to trigger custom formatting.
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)
}
}
fn main() {
let p = Pair { x: 1, y: 2 };
println!("Custom format: {}", p);
}