Implement the Display trait to define custom string formatting for your Rust types.
Implement the std::fmt::Display trait for your type to define custom formatting for end users.
use std::fmt;
struct User {
username: String,
}
impl fmt::Display for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "User: {}", self.username)
}
}
fn main() {
let user = User { username: "alice".to_string() };
println!("{user}");
}
std::fmt lets you decide exactly how your custom data types look when printed to the screen. Think of it like designing a business card: you control the layout and information shown to the public, rather than showing the raw internal data. You use this whenever you want to present your data in a user-friendly way instead of a technical debug format.