Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Collections

Rust HashMap<K, V> type

Reference for Rust HashMap<K, V>: creating maps, key requirements (Eq + Hash), ownership, iteration order, capacity, SipHash and common mistakes.

HashMap<K, V> in std::collections stores key-value pairs in a hash table. Looking up, inserting and removing a key take O(1) time on average. Each key appears at most once; inserting an existing key replaces its value.

The key type must implement Eq and Hash, and the two must agree: keys that are equal must produce the same hash. Floats do not implement Eq, so f64 cannot be a key directly. The iteration order is unspecified and changes from run to run, because the default hasher is randomly seeded. Never depend on it; sort the keys when you need stable output.

Rust
use std::collections::HashMap;

let mut ages: HashMap<String, u32> = HashMap::new();
ages.insert("Ann".to_string(), 31);

Try it

Rust Building and reading a map

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 Ownership and a missing key panic

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 struct HashMap<K, V, S = RandomState> { /* private */ }

impl<K, V> HashMap<K, V, RandomState> {
    pub fn new() -> HashMap<K, V, RandomState>;
    pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState>;
}

impl<K: Eq + Hash, V, S: BuildHasher> HashMap<K, V, S> {
    pub fn insert(&mut self, k: K, v: V) -> Option<V>;
    pub fn get<Q>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Hash + Eq + ?Sized;
    pub fn remove<Q>(&mut self, k: &Q) -> Option<V> where K: Borrow<Q>, Q: Hash + Eq + ?Sized;
    pub fn entry(&mut self, key: K) -> Entry<'_, K, V>;
    pub fn len(&self) -> usize;
    pub fn reserve(&mut self, additional: usize);
}
Name Description
K Key type; must implement Eq and Hash for lookups.
V Value type; no requirements.
S The hasher builder; defaults to RandomState (SipHash 1-3 with random keys).
capacity Number of entries to make room for without reallocating.

Returns: insert returns the old value if the key was present, otherwise None. get returns Option<&V>.

Errors and panics: map[&key] panics if the key is missing; use get when absence is normal. A key whose Hash or Eq changes while it is in the map (through interior mutability) leads to unspecified, but memory-safe, behavior. Allocation failure aborts.

Usage notes

  • Lookup by borrowed form: a HashMap<String, V> can be queried with &str because String: Borrow<str>. Their Hash and Eq agree, which is what makes this work.
  • HashMap::new() does not allocate until the first insert. Use with_capacity or reserve when you know the size to avoid rehashing.
  • Iteration order is random per map instance. For deterministic output collect and sort, or use BTreeMap.
  • Default hasher: SipHash resists hash-flooding attacks but is not the fastest. For trusted integer keys a custom BuildHasher can be quicker; see Hash, Hasher and RandomState.
  • Updating in place: prefer the entry API to "check then insert", which hashes twice.
  • Ownership: insert moves the key and value into the map. Clone first if you still need them.
  • No f32/f64 keys (no Eq). Wrap them with a type that orders by bits, or use integers.
  • Equality: two maps are == when they hold the same pairs, regardless of order.
  • Construct from arrays with HashMap::from([(k, v), ...]) (Rust 1.56+).