Sub topic 11
Common Standard Library Traits and #[derive]
This chapter assumes you can define structs and enums, write and implement a basic trait, and use generics with trait bounds. It covers the standard library traits you will implement most often, and how #[derive] writes many of those implementations for you.
Why these traits matter
Much of the standard library is written against traits. println!("{:?}", x) needs Debug. == needs PartialEq. HashMap keys need Eq and Hash. If your type implements the right traits, it works with all of that code.
| Trait | What it gives you | Typical use |
|---|---|---|
| `Debug` | `{:?}` formatting for programmers | Logging, `assert_eq!` failure output |
| `Display` | `{}` formatting for users | Messages, `to_string()` |
| `Clone` | Explicit duplicate with `.clone()` | Copying heap data |
| `Copy` | Implicit bitwise copy | Small plain values |
| `PartialEq`, `Eq` | `==` and `!=` | Comparing, hash map keys |
| `PartialOrd`, `Ord` | `<`, `>`, sorting | `sort()`, `max()` |
| `Hash` | Hashing | `HashMap` and `HashSet` keys |
| `Default` | `Type::default()` | Initial values, struct update syntax |
Using #[derive]
#[derive] is an attribute that asks the compiler to generate a standard implementation. For a struct, the generated code applies the trait to each field in turn. So every field must implement that trait too.
use std::collections::HashMap;
#[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 = Version { major: 1, minor: 10 };
println!("{:?}", a);
println!("{}", a < b);
println!("{:?}", Version::default());
let mut notes: HashMap<Version, &str> = HashMap::new();
notes.insert(a.clone(), "first");
println!("{:?}", notes.get(&a));
}For PartialOrd and Ord, derive compares fields in declaration order. Here major is compared first, then minor. Reordering the fields changes the ordering.
Writing Display by hand
Display cannot be derived, because the compiler cannot know how you want a type shown to users. You implement fmt and write into the formatter.
use std::fmt;
struct Celsius(f64);
impl fmt::Display for Celsius {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:.1} °C", self.0)
}
}
fn main() {
let t = Celsius(21.456);
println!("{}", t);
println!("{}", t.to_string());
}Implementing Display also gives you to_string() for free, through a blanket implementation in the standard library.
Partial versus total
PartialEq and PartialOrd are "partial" because some types have values that do not compare normally. The standard example is f64, where NaN == NaN is false. A type containing an f64 can derive PartialEq but not Eq, and so cannot be a HashMap key.
Clone versus Copy
Clone is explicit and may be expensive, as with cloning a String. Copy is implicit and always a cheap bitwise copy. A type can be Copy only if all its fields are Copy, and it must also implement Clone. A type that owns heap data, such as String or Vec, can never be Copy.
Common errors
- Deriving a trait when a field's type lacks it. The error points at the field.
- Deriving
Copyon a type with aStringfield. - Implementing
Hashby hand in a way that disagrees withPartialEq. Equal values must produce equal hashes. - Deriving
Defaulton an enum without marking a#[default]variant.
Exercise
You write #[derive(Debug, Clone, Copy)] struct Label { text: String }. Why does it fail to compile, and what is the smallest change that fixes it?
Show answer
Copy requires every field to be Copy, and String owns heap memory, so it is not Copy. Remove Copy from the derive list and keep Clone. Callers then write .clone() explicitly. Alternatively, change the field to &'static str, which is Copy.