#[derive(Debug, Clone, PartialEq)]
The #[derive] attribute in Rust lets you automatically implement traits such as Debug, Clone, and PartialEq. This eliminates the need for manual implementations and significantly reduces boilerplate code.
Syntax
// Automatically implement traits using the derive attribute.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
struct Point {
x: i32,
y: i32,
}
// Debug: print the value using {:?} or {:#?}.
let p = Point { x: 1, y: 2 };
println!("{:?}", p); // Point { x: 1, y: 2 }
println!("{:#?}", p); // Pretty-printed output.
// Clone: create a deep copy with .clone().
let p2 = p.clone();
// PartialEq: compare values with ==.
assert_eq!(p, p2);
// Default: create an instance with default values (numbers are 0, bool is false, String is String::new()).
let zero = Point::default(); // Point { x: 0, y: 0 }
Common derive traits
| Trait | Description |
|---|---|
| Debug | Enables debug output via {:?} / {:#?}. Recommended for use during development at all times. |
| Clone | Enables deep copying with .clone(). Heap-allocated data such as String is also copied. |
| Copy | Enables implicit copying on assignment (also requires Clone). Can only be used when all fields implement Copy. |
| PartialEq | Enables comparison with == / !=. Compares all fields. |
| Eq | Extends PartialEq to indicate full equivalence. Cannot be used with types that have NaN values, such as f64. |
| PartialOrd | Enables ordering comparisons with < / > / <= / >= (also requires PartialEq). |
| Ord | Enables total ordering (e.g., for sorting) (also requires PartialOrd, Eq, and PartialEq). |
| Hash | Allows use as a HashMap key (also requires Eq). |
| Default | Enables creating an instance with default values via ::default(). |
Sample code
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
struct Color {
r: u8,
g: u8,
b: u8,
}
#[derive(Debug, Clone, PartialEq)]
struct Player {
name: String,
score: i32,
color: Color,
}
fn main() {
// Debug: print debug output.
let red = Color { r: 255, g: 0, b: 0 };
println!("{:?}", red); // Color { r: 255, g: 0, b: 0 }
println!("{:#?}", red); // Pretty-printed output.
// Clone: create a deep copy.
let red2 = red.clone();
println!("cloned: {:?}", red2);
// PartialEq: compare with ==.
println!("red == red2: {}", red == red2); // true
let blue = Color { r: 0, g: 0, b: 255 };
println!("red == blue: {}", red == blue); // false
// Hash: use as a HashMap key.
let mut palette: HashMap<Color, &str> = HashMap::new();
palette.insert(red.clone(), "red");
palette.insert(blue.clone(), "blue");
println!("palette: {:?}", palette.get(&red)); // Some("red")
// Default: create an instance with default values (all zeros).
let black = Color::default();
println!("default color: {:?}", black); // Color { r: 0, g: 0, b: 0 }
// Clone and PartialEq with nested structs.
let p1 = Player {
name: String::from("Alice"),
score: 100,
color: red.clone(),
};
let p2 = p1.clone();
println!("p1 == p2: {}", p1 == p2); // true
// A struct using PartialOrd and Ord (when all fields implement Ord).
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Version {
major: u32,
minor: u32,
patch: u32,
}
let mut versions = vec![
Version { major: 1, minor: 2, patch: 0 },
Version { major: 2, minor: 0, patch: 0 },
Version { major: 1, minor: 1, patch: 5 },
];
versions.sort();
println!("sorted versions: {:?}", versions);
}
Notes
#[derive] can only be used when all fields of the struct also implement the same trait. For example, Copy can only be derived if every field implements Copy.
PartialEq compares all fields of a struct in order. If you need to compare only specific fields or require custom floating-point comparison, implement the trait manually.
For struct definitions, see struct / Field definitions. For method definitions, see impl / Method definitions.
If you find any errors or copyright issues, please contact us.