#[derive(...)] is Rust's way of auto-generating trait implementations at compile time. Instead of writing boilerplate code manually, the compiler generates it for you based on your struct or enum's fields.
#[derive(Debug, Clone, PartialEq)]
struct Order {
id: u64,
symbol: String,
quantity: f64,
}
The compiler expands this into full trait implementations — you get Debug, Clone, and PartialEq for free.
| Trait | Purpose | Use Case |
|---|---|---|
Debug |
Format with {:?} |
Logging, debugging |
Clone |
Deep copy via .clone() |
Duplicating owned data |
Copy |
Implicit bitwise copy (requires Clone) |
Small, stack-only types |
PartialEq |
== and != comparison |
Equality checks |
Eq |
Marker for total equality (requires PartialEq) |
HashMap keys |
PartialOrd |
<, >, <=, >= comparison |
Sorting |
Ord |
Total ordering (requires PartialOrd + Eq) |
BTreeMap keys |
Hash |
Compute hash value | HashMap/HashSet keys |
Default |
Create default instance via Default::default() |
Builder patterns |
Derived PartialEq compares all fields using logical AND:
#[derive(PartialEq)]
struct Trade {
symbol: String,
price: f64,
timestamp: u64,
}
// a == b is true only if:
// a.symbol == b.symbol && a.price == b.price && a.timestamp == b.timestamp
Derived PartialOrd compares fields in declaration order, like dictionary sorting:
#[derive(PartialEq, PartialOrd)]
struct Trade {
symbol: String, // compared first
price: f64, // compared second (if symbol equal)
timestamp: u64, // compared third (if price equal)
}
let a = Trade { symbol: "BTC".into(), price: 100.0, timestamp: 1 };
let b = Trade { symbol: "BTC".into(), price: 200.0, timestamp: 1 };
a < b // true — same symbol, but 100.0 < 200.0
If you need custom comparison logic (e.g., compare only by timestamp), implement the trait manually instead of deriving.
Floats break mathematical rules:
NaN != NaN (not reflexive)