How to Derive Common Traits Automatically in Rust

Use the #[derive] attribute above a struct to automatically generate implementations for common traits like Debug, Clone, and PartialEq.

You derive common traits automatically by adding a #[derive(...)] attribute above your struct definition. This instructs the compiler to generate the necessary implementation code for the specified traits, such as Debug for printing or Clone for copying.

#[derive(Debug, Clone, PartialEq)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    let rect2 = rect1.clone();
    println!("rect1 is {rect1:?}");
    println!("rect1 == rect2: {}", rect1 == rect2);
}