Sub topic 11
Common standard library traits and #[derive]
This chapter assumes you can define a struct and an enum, write a trait and an impl block, and read a generic bound such as T: Clone. You should also know the basic ownership rules about moves and borrows.
The standard library defines a small set of traits that nearly every Rust type implements. Many functions and collections depend on them. println!("{:?}", x) needs Debug. HashMap keys need Hash and Eq. .sort() needs Ord. Learning this set lets you read most library signatures.
What #[derive] does
#[derive(...)] is an attribute that asks the compiler to generate a trait implementation for you. The generated code applies the trait to each field in turn. Derive works only if every field's type already implements the trait.
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
struct Version {
major: u32,
minor: u32,
}
fn main() {
let a = Version { major: 1, minor: 2 };
let b = a.clone();
let c = Version::default();
println!("{} {:?}", a == b, c);
println!("{}", a > c);
let mut set = HashSet::new();
set.insert(a);
set.insert(b);
println!("{}", set.len());
}This prints true Version { major: 0, minor: 0 }, then true, then 1. The set holds one element because a and b are equal and hash the same.
The traits you will meet most
| Trait | What it provides | Derivable |
|---|---|---|
| `Debug` | Developer-facing text with `{:?}` | Yes |
| `Display` | User-facing text with `{}` | No |
| `Clone` | Explicit duplicate with `.clone()` | Yes |
| `Copy` | Implicit bitwise copy on assignment | Yes |
| `PartialEq`, `Eq` | `==` and `!=` | Yes |
| `PartialOrd`, `Ord` | `<`, `>`, `.sort()`, `.max()` | Yes |
| `Hash` | Hashing for `HashMap` and `HashSet` keys | Yes |
| `Default` | `T::default()`, a standard starting value | Yes |
| `From`, `Into` | Infallible conversions between types | No |
Display is not derivable because the compiler cannot guess how you want a user to see your type. From is not derivable because a conversion needs a specific rule.
How the traits depend on each other
Several of these traits are supertraits of others. A supertrait is a trait that another trait requires. You cannot implement the child without the parent.
When you derive Ord, also derive Eq, PartialOrd, and PartialEq. When you derive Copy, also derive Clone. The compiler reports an error if a required trait is missing.
Debug and Display
Debug is for programmers: logs, dbg!, and test failure messages. Derive it on almost every type. Display is for end users, and you write it by hand.
use std::fmt;
#[derive(Debug)]
struct Celsius(f64);
struct Fahrenheit(f64);
impl fmt::Display for Celsius {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:.1}°C", self.0)
}
}
impl From<Fahrenheit> for Celsius {
fn from(temp: Fahrenheit) -> Self {
Celsius((temp.0 - 32.0) * 5.0 / 9.0)
}
}
fn main() {
let c: Celsius = Fahrenheit(212.0).into();
println!("{c}");
println!("{c:?}");
}The output is 100.0°C followed by Celsius(100.0).
Implementing Display also gives you .to_string(), because the standard library has a blanket implementation of ToString for every T: Display. A blanket implementation is an impl that covers all types meeting a bound.
From and Into
Implement From<A> for B and you get Into<B> for A automatically. Write From, and call .into() at the use site. In your own function signatures, prefer impl Into<String> for arguments that callers may pass as &str or String.
The ? operator also uses From. When a function returns Result<T, MyError>, ? converts an error E into MyError by calling MyError::from(e). Implementing From<io::Error> for MyError lets you use ? on I/O calls.
Clone and Copy
Clone makes a duplicate on request and can be expensive, as with a Vec or String. Copy is a marker for types where a bitwise copy is a complete duplicate. A Copy value is not moved on assignment. The original stays usable.
#[derive(Debug, Clone, Copy)]
struct Pixel {
x: u16,
y: u16,
}
fn main() {
let a = Pixel { x: 1, y: 2 };
let b = a;
println!("{a:?} {b:?}");
}This compiles because Pixel is Copy. Without Copy on the derive line, the println! would fail with a "borrow of moved value" error.
A type can be Copy only if all its fields are Copy. A String field rules it out, because String owns heap memory. Also, a type that implements Drop cannot be Copy.
Equality, ordering, and hashing
Why are there two equality traits? PartialEq allows values that are not equal to themselves. f64::NAN == f64::NAN is false. Eq is an extra promise that equality is reflexive, so every value equals itself. Floating point types implement PartialEq but not Eq.
The same split applies to ordering. PartialOrd::partial_cmp returns Option<Ordering>, and None means the values cannot be compared. Ord::cmp always returns an Ordering.
Derived ordering is lexicographic. It compares fields in declaration order, and the first difference decides. For enums, variants compare by their declaration order before any data is compared. Reordering fields or variants changes the behavior of derived Ord, so treat declaration order as part of your API.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Level {
Low,
Mid,
High,
}
fn main() {
let mut levels = vec![Level::High, Level::Low, Level::Mid];
levels.sort();
println!("{levels:?}");
println!("{:?}", levels.iter().max());
}The output is [Low, Mid, High] and then Some(High).
Hash has a rule that the compiler cannot check. If a == b, then their hashes must be equal. Deriving both PartialEq and Hash satisfies this. Mixing a hand-written PartialEq with a derived Hash can break it, and a HashMap will then miss keys it should find.
Default
Default supplies a sensible starting value. Numbers become 0, bool becomes false, String and Vec become empty, and Option becomes None. Deriving Default on a struct uses the default of every field. Combine it with struct update syntax to set only some fields.
#[derive(Debug, Default)]
struct Config {
name: String,
retries: u32,
verbose: bool,
}
fn main() {
let cfg = Config {
retries: 3,
..Default::default()
};
println!("{cfg:?}");
}This prints Config { name: "", retries: 3, verbose: false }. For enums, derive Default by marking one unit variant with #[default].
Common errors
- "the trait bound
X: Traitis not satisfied" on a derive. One of the fields lacks the trait. Derive the trait on that field's type, or implement it by hand. - Deriving
EqorOrdon a struct with anf64. This fails becausef64is onlyPartialEqandPartialOrd. Wrap the value, or compare withf64::total_cmp. - Using
{}on a type with onlyDebug. The compiler says the type does not implementstd::fmt::Display. Use{:?}or implementDisplay. - Overusing
.clone()to silence the borrow checker. It compiles, but it hides an ownership question and can copy large data. Try borrowing first. - Adding
Copyto a type that may grow. RemovingCopylater breaks every caller that relied on implicit copies. Add it only when the type is small and plain.
Exercise
You have #[derive(PartialEq, Eq, Hash)] struct Id(u32); and want to use Id as a HashMap key and also sort a Vec<Id>. What must you add, and which other traits does it depend on?
Show answer
Add PartialOrd and Ord to the derive list. Ord requires Eq and PartialOrd, and PartialOrd requires PartialEq. Those are already present or added together. The HashMap key use already works with Eq and Hash. Sorting then uses the derived lexicographic order, which here compares the single u32 field.
Exercise
A struct has a name: String field. Why does #[derive(Clone, Copy)] on it fail, and what is the fix?
Show answer
Copy requires every field to be Copy, and String owns heap memory, so it is not Copy. Remove Copy and keep Clone. Callers then use .clone() for duplicates and pass references to avoid moves.