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);
}
The #[derive] attribute tells the Rust compiler to automatically write the boilerplate code needed for your struct to support common behaviors like printing, copying, or comparing. Instead of manually writing the implementation for every trait, you simply list the trait names in the attribute, and the compiler handles the rest. Think of it as asking the compiler to fill out a standard form for your data structure so it works with the rest of the language immediately.