9.12 Derived Traits
Traits like Debug, Clone, Copy, PartialEq, and Default can often be automatically derived for a struct using #[derive(...)].
9.12.1 Common Traits
Debug: Enables formatting with{:?}Clone: Allows creating a deep copy of the valueCopy: Requires all fields to also beCopytypesPartialEq: Enables==and!=Default: Provides a default constructor
9.12.2 Example: Debug
#[derive(Debug)] struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 1, y: 2 }; println!("{:?}", p); // Compact println!("{:#?}", p); // Pretty-printed }
9.12.3 Implementing Traits Manually
impl std::fmt::Display for Point {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Point({}, {})", self.x, self.y)
}
}