Sub topic 1
Rust Standard Traits: Debug, Display, From, and Default
Prerequisites
Assume you know Rust structs, ownership and borrowing, traits, impl, println!, and basic Result and Option use.
Standard traits as shared contracts
A trait is a shared contract. It describes operations a type supports without deciding how the type stores its data. A trait implementation connects that contract to a specific type.
Rust’s standard traits give common types predictable behavior:
Debugprovides developer-focused formatting.Displayprovides user-focused formatting.Fromdefines a conversion into a type.Defaultdefines a standard initial value.
Getting implementations for free with derive
The #[derive(...)] attribute asks the compiler to generate a standard implementation. A type can derive a trait when all required fields support that trait.
Debug: printing values for developers
Debug is intended for inspection, logs, and troubleshooting. Use {:?} for compact output and {:#?} for pretty, indented output.
use std::fmt;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
struct Credentials {
user: String,
password: String,
}
impl fmt::Debug for Credentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Credentials")
.field("user", &self.user)
.field("password", &"<hidden>")
.finish()
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let point = Point { x: 1, y: 2 };
println!("{:?}", point);
println!("{:#?}", point);
println!("{}", point);
}Deriving Debug is usually best. Implement it manually when the default output exposes secrets, contains too much data, or needs a different shape. The debug_struct builder preserves familiar debug formatting while letting you choose each field.
Display: printing values for users
Display defines the readable output used by {}. Implement it with write! and the supplied Formatter. Once a type implements Display, Rust automatically provides to_string(), so the same type can produce a String when needed.
Choose Debug to inspect a value. Choose Display to communicate what the value means.
Exercise
Which formatter should you use for a user-facing message, {:?} or {}?
Show answer
Use {} because it uses the type's Display implementation.