9.13 Derived Traits

Rust allows you to automatically implement certain traits for your structs using the #[derive] attribute.

9.13.1 Common Traits

  • Debug: Allows formatting using {:?}.
  • Clone: Allows cloning of instances.
  • Copy: Allows bitwise copying (requires all fields to implement Copy).
  • PartialEq: Enables equality comparisons using == and !=.
  • Default: Provides a default value for the type.

9.13.2 Example: Deriving Debug

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}
fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{:?}", p);    // Prints: Point { x: 1, y: 2 }
    println!("{:#?}", p);   // Pretty-prints the struct
}
  • Using {:?} formats the struct in a compact way.
  • Using {:#?} pretty-prints the struct with indentation.

Output:

Point { x: 1, y: 2 }
Point {
    x: 1,
    y: 2,
}

9.13.3 Implementing Traits Manually

You can also implement traits manually to customize behavior.

Implementing Default Manually:

impl Default for Point {
    fn default() -> Self {
        Point { x: 0, y: 0 }
    }
}

Implementing Display 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)
    }
}