Skip to content
Tutorials Center
My learning

Topics

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.

Rust
#[derive(PartialEq, Eq, Hash)]
struct UserId(u64);

Try it

Rust Derived Hash as a map key

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.

Rust Manual Hash and a hasher

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

Rust
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 == b then hash(a) == hash(b). The reverse need not hold (collisions are allowed). Hash exactly the data that eq compares, nothing more.
  • Derive both or write both. derive(Hash) with a hand-written PartialEq that ignores a field breaks the contract and makes lookups miss.
  • Floats are not Hash because they are not Eq. Key by to_bits(), by a rounded integer, or by an ordered wrapper.
  • str, String and &str hash alike, which is why you can look up a HashMap<String, V> with a &str: see Borrow.
  • Default hasher: HashMap uses 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 a BuildHasher. Crates such as rustc-hash or ahash provide faster ones, and std::hash::BuildHasherDefault<H> builds one from a Default hasher. Faster hashers are not in std, so real projects usually add a crate for them.
  • Collections: Vec<T>, tuples, Option<T>, Box<T> and arrays are Hash when their contents are. HashMap and HashSet themselves are not (unordered), but BTreeMap and BTreeSet are.
  • 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.