Rust Reference ยท Core Traits
The Hash trait
Reference for the Rust Hash and Hasher traits: derive Hash, the Hash and Eq contract, custom impls, DefaultHasher, BuildHasher and why SipHash is the default.
Hash describes how a value feeds its data into a hasher. HashMap and HashSet use it to pick a bucket for a key, together with Eq to confirm a match. A type is a valid key when it implements both.
You almost always derive it. The trait has one required method, hash, which writes the value into any Hasher. Turning that into a number is the hasher's job, not the type's.
#[derive(PartialEq, Eq, Hash)] struct UserId(u64);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait Hash { fn hash<H: Hasher>(&self, state: &mut H); fn hash_slice<H: Hasher>(data: &[Self], state: &mut H) where Self: Sized; } pub trait Hasher { fn finish(&self) -> u64; fn write(&mut self, bytes: &[u8]); // write_u8, write_u32, write_usize, ... have default methods }
| Name | Description |
|---|---|
state |
The hasher to feed. Call field.hash(state) for every field that takes part in equality. |
finish |
Returns the 64-bit hash of everything written so far. It does not reset the hasher. |
Usage notes
- The contract: if
a == bthenhash(a) == hash(b). The reverse need not hold (collisions are allowed). Hash exactly the data thateqcompares, nothing more. - Derive both or write both.
derive(Hash)with a hand-writtenPartialEqthat ignores a field breaks the contract and makes lookups miss. - Floats are not
Hashbecause they are notEq. Key byto_bits(), by a rounded integer, or by an ordered wrapper. str,Stringand&strhash alike, which is why you can look up aHashMap<String, V>with a&str: seeBorrow.- Default hasher:
HashMapuses SipHash 1-3 with random keys per map, which resists collision attacks but is slower than simple hashes. The output is not stable between runs or Rust versions, so never store or compare hash values across processes. - Custom hashers:
HashMap<K, V, S>takes aBuildHasher. Crates such asrustc-hashorahashprovide faster ones, andstd::hash::BuildHasherDefault<H>builds one from aDefaulthasher. Faster hashers are not instd, so real projects usually add a crate for them. - Collections:
Vec<T>, tuples,Option<T>,Box<T>and arrays areHashwhen their contents are.HashMapandHashSetthemselves are not (unordered), butBTreeMapandBTreeSetare. - Prefix collisions: the derived impl for strings and slices also writes a length or terminator, so
("ab", "c")and("a", "bc")hash differently. Do the same in manual impls with variable-length parts.