Derive macros for automatic trait implementations
Marcus Chen
Jan 2026
1 tab
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = p1.clone();
println!("{:?}", p1);
assert_eq!(p1, p2);
}
1 file · rust
Explain with highlit
Rust's #[derive] attribute auto-generates trait implementations for common traits like Debug, Clone, PartialEq, and Serialize. This eliminates boilerplate and ensures consistency. For example, #[derive(Debug)] generates a debug formatter that prints all fields. Custom derive macros (from crates like serde or thiserror) can generate complex code based on the struct definition. I derive Debug and Clone on almost every type during development. For production, I add Serialize and Deserialize for data that crosses boundaries. Derive macros are a form of compile-time metaprogramming that keeps code DRY without runtime cost. It's one of the features that makes Rust feel high-level despite being systems-focused.