Sub topic 13
What Makes a Type Usable as a Key
This chapter assumes you know basic HashMap operations (insert, get, remove), ownership and borrowing, and how to derive traits on structs.
The two requirements
A HashMap<K, V> finds an entry by turning the key into a number (a hash) and then comparing keys that land in the same slot. So the key type K needs two traits:
Hash, which feeds the key's data into a hasher to produce the number.Eq, which says when two keys are the same.Eqbuilds onPartialEqand adds the promise that every value equals itself.
Methods like insert and get only exist when K: Eq + Hash. HashMap::new() has no such bound, so the error appears at your first insert or get.
Deriving the traits
If every field of a struct implements Hash and Eq, derive them. You must derive PartialEq too, because Eq requires it.
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Hash)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut labels: HashMap<Point, &str> = HashMap::new();
labels.insert(Point { x: 0, y: 0 }, "origin");
labels.insert(Point { x: 1, y: 2 }, "A");
println!("{:?}", labels.get(&Point { x: 0, y: 0 })); // Some("origin")
}The lookup builds a new Point and still finds the entry. Keys match by value, not by identity.
Enums, tuples, String, &str, integers, bool, char and Vec<T> (when T qualifies) already work as keys. A tuple such as (i32, i32) is often simpler than a one-off struct.
Types that cannot be keys
f32 and f64 do not implement Eq or Hash. The value NaN is not equal to itself, which breaks the Eq promise. If you need float keys, store a scaled integer, or wrap the bits with f64::to_bits in your own type.
HashMap and HashSet also lack Hash, because their iteration order is not fixed. A BTreeMap key can serve as a sorted alternative.
The rule that hash and equality must agree
If a == b, then a and b must produce the same hash. Derived implementations always satisfy this. If you write them by hand, keep them consistent, and hash exactly the fields that == compares. A broken pairing does not fail to compile. It makes lookups miss entries that are present.
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
struct User {
id: u32,
last_seen: u64, // changes often, not part of identity
}
impl PartialEq for User {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for User {}
impl Hash for User {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state); // same field as eq
}
}
fn main() {
let mut roles: HashMap<User, &str> = HashMap::new();
roles.insert(User { id: 7, last_seen: 100 }, "admin");
let probe = User { id: 7, last_seen: 999 };
println!("{:?}", roles.get(&probe)); // Some("admin")
}Two User values with the same id are equal and hash alike, so last_seen does not affect the lookup.
Lookups with borrowed forms
HashMap<String, V> accepts a &str in get and remove. This works because String: Borrow<str>, and str hashes and compares the same way String does. You can query without allocating a new String.
Exercise
You write #[derive(Hash, Eq)] on a struct and use it as a HashMap key. The compiler rejects it. What is missing, and why?
Show answer
PartialEq is missing. Eq is a marker on top of PartialEq, so the struct needs #[derive(PartialEq, Eq, Hash)].
Exercise
Why can't f64 be a HashMap key, and what is one workaround?
Show answer
f64 has NaN, which is not equal to itself, so f64 cannot implement Eq (and so not Hash). One workaround is to key on f64::to_bits(x) as a u64, or on a scaled integer.