Sub topic 13
What Makes a Type Usable as a Key
This chapter assumes you know Rust structs and enums, the basics of traits and #[derive], and the HashMap operations from the earlier chapters (insert, get, entry). It explains which types can be keys, why the compiler asks for those traits, and how to write the traits by hand when derive is not enough.
The two trait bounds
HashMap::new() accepts any key type. The restriction applies to the methods that use the key, such as insert, get, remove and entry. Those methods require K: Eq + Hash.
Hashlets the map turn a key into a number (a hash) that picks a bucket.Eqlets the map confirm that two keys in the same bucket are really the same key. Different keys can produce the same hash, so a matching hash alone does not prove equality.
Eq is a marker trait that builds on PartialEq. It promises that equality is total: every value equals itself (a == a), and == is symmetric and transitive.
The rule that ties them together
The two traits must agree:
if a == b, then hash(a) == hash(b)If two equal keys hash differently, the map looks in the wrong bucket and misses an entry that is present. Nothing is unsafe, but lookups return wrong answers. The reverse is allowed. Two unequal keys may share a hash, and that only costs speed.
Deriving both traits
Deriving is the right choice when equality should compare every field. derive generates PartialEq, Eq and Hash so they agree with each other. It works when every field type also implements those traits.
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Suit {
Hearts,
Spades,
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct CardKey {
suit: Suit,
rank: u8,
owner: String,
}
fn main() {
let mut counts: HashMap<CardKey, u32> = HashMap::new();
counts.insert(
CardKey { suit: Suit::Spades, rank: 12, owner: String::from("ana") },
1,
);
counts.insert(
CardKey { suit: Suit::Hearts, rank: 3, owner: String::from("bo") },
4,
);
let probe = CardKey { suit: Suit::Spades, rank: 12, owner: "ana".to_string() };
println!("{:?}", counts.get(&probe)); // Some(1)
// Tuples of hashable types are hashable too.
let mut grid: HashMap<(i32, i32), char> = HashMap::new();
grid.insert((0, 0), '#');
println!("{:?}", grid.get(&(0, 0))); // Some('#')
}The probe is a separate CardKey value, yet the lookup succeeds because equality compares field contents, not memory addresses.
Common key types that work out of the box:
| Key type | Usable? | Notes |
|---|---|---|
| Integers, `bool`, `char` | Yes | Cheapest keys to hash. |
| `String`, `&str` | Yes | `String` keys can be queried with `&str`. |
| Tuples, arrays | Yes | Only if every element is `Eq + Hash`. |
| `Vec<T>`, `Option<T>` | Yes | Only if `T` is `Eq + Hash`. |
| `f32`, `f64` | No | Not `Eq` and not `Hash`. |
| `HashMap`, `HashSet` | No | They do not implement `Hash`. Use `BTreeMap` or `BTreeSet`, which do. |
| Your struct or enum | If derived | Every field type must support the traits. |
Why floats are rejected
f64 implements PartialEq but not Eq. The value NaN is not equal to itself, which breaks the promise a == a. A map could store a NaN key and never find it again. Also, 0.0 == -0.0 is true even though their bit patterns differ, so a bit-based hash would break the equality rule above.
The compiler reports this when you call insert or get on a HashMap<f64, _>. It says f64 does not implement Eq or Hash. A struct that contains an f64 field cannot derive these traits for the same reason.
The usual fix is to key on an exact integer representation:
use std::collections::HashMap;
fn main() {
let mut prices: HashMap<u64, &str> = HashMap::new();
let price = 19.99_f64;
let cents = (price * 100.0).round() as u64; // 1999
prices.insert(cents, "book");
println!("{:?}", prices.get(&1999)); // Some("book")
}Rounding matters. Multiplying 19.99 by 100.0 gives 1998.9999999999998, and a plain cast would truncate that to 1998. If you need to key on arbitrary floats, a wrapper type that rejects NaN and normalizes -0.0 is the other option. Crates such as ordered-float provide one.
Writing the traits by hand
Sometimes equality should not compare every field. Examples are case-insensitive names, or a record identified only by its id. Then you implement both traits yourself and keep them consistent.
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
#[derive(Debug)]
struct Username(String);
impl PartialEq for Username {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(&other.0)
}
}
impl Eq for Username {}
impl Hash for Username {
fn hash<H: Hasher>(&self, state: &mut H) {
// Hash the lowercase bytes so "Alice" and "ALICE" hash identically.
for b in self.0.bytes() {
state.write_u8(b.to_ascii_lowercase());
}
state.write_u8(0xff); // end marker, as str's own Hash does
}
}
fn main() {
let mut logins: HashMap<Username, u32> = HashMap::new();
logins.insert(Username("Alice".to_string()), 1);
*logins.entry(Username("ALICE".to_string())).or_insert(0) += 10;
println!("{}", logins.len()); // 1
println!("{:?}", logins.get(&Username("alice".to_string()))); // Some(11)
}eq ignores case, so hash must ignore case too. If hash used the raw bytes, "Alice" and "ALICE" would be equal but would usually land in different buckets, and the map would often hold two entries for one logical user.
Notice that entry kept the original key "Alice" and only updated the value. When a map already holds an equal key, it keeps the stored key and drops the new one.
The Eq implementation is empty on purpose. It is a promise from you, and the compiler does not check it.
Looking up with a borrowed form
Earlier you called stock.get("apple") on a HashMap<String, u32>. This works because get is generic over a borrowed form of the key:
fn get<Q>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq + ?SizedString implements Borrow<str>, so you can search with a &str and avoid allocating a String just to look something up. Vec<u8> works the same way with &[u8]:
use std::collections::HashMap;
fn main() {
let mut blobs: HashMap<Vec<u8>, u32> = HashMap::new();
blobs.insert(vec![1, 2], 7);
let probe: &[u8] = &[1, 2];
println!("{:?}", blobs.get(probe)); // Some(7)
}The contract here is that the borrowed form must hash and compare exactly like the owned form. Standard types satisfy this. If you implement Borrow for your own key type, you take on that obligation.
Keys should not change while stored
The map owns its keys and does not hand out &mut K, so ordinary code cannot change a key in place. The loophole is interior mutability. A key containing a Cell, RefCell or similar can change its hash after insertion, and the entry becomes unreachable. This is a logic error. It does not cause undefined behavior, but the entry may be lost, and lookups may find the wrong one. Use keys that are plain immutable data.
Choosing derive or a manual implementation
- Derive when two keys are equal exactly when all their fields are equal.
- Implement by hand when equality is a subset of the fields or a normalized form, and make
hashuse the same subset or normalization. - Prefer small keys. Hashing a long
Stringor a large struct on every lookup costs time, so consider an integer id instead. - If you need ordering or sorted iteration rather than hashing,
BTreeMaprequiresOrdinstead ofHash. Floats still fail there, becausef64is notOrd.
Exercise
You write impl PartialEq for Tag so that two tags are equal when their name fields match, ignoring the color field. You then add #[derive(Hash)] to Tag, which hashes both name and color. What goes wrong when you use Tag as a HashMap key, and how do you fix it?
Show answer
Two tags with the same name but different colors are equal under == yet produce different hashes. The map usually looks in the wrong bucket, so get can miss an entry that exists, and insert can store two entries that count as the same key. The fix is to implement Hash by hand and hash only name, so equal tags always hash equally. Also add impl Eq for Tag {}.
Exercise
Why can you not use HashMap<f64, String> for a table of measurements, and what is one safe alternative key?
Show answer
f64 implements neither Eq (because NaN != NaN) nor Hash, so the map's insert and get methods do not compile for it. A safe alternative is an integer key such as measurement in thousandths ((x * 1000.0).round() as i64), or a wrapper type from a crate such as ordered-float that excludes NaN.