HashMap and HashSet: resources¶
Beside A first HashMap and A first HashSet · companions: every error · lints
Level: reference · the reading list
One line: Where the rest of the Rust world explains hash maps and sets: the Book's chapter and its six sections, what three books on the shelf say and where, the std pages that matter (HashMap, HashSet, Entry, the which collection table, RandomState and the HashDoS note, Borrow), the crate underneath (hashbrown) and the design it follows, the error codes, the lints, and three places to read with care — including §5.5–5.6 of Rust: The Practical Guide, which prints its maps unsorted and says contains_key returns an Option.
Every entry was checked on 2026-09-23 and every URL again on 2026-09-24: each answered 200 to curl (crates.io and the two publishers' sites refuse scripted requests, so hashbrown is linked at docs.rs and GitHub, and the book sections come from the books themselves), and each #anchor named here exists on its page. Book sections are copied from each book's own table of contents, read on this machine. The video's title was checked; it was not watched, so no timestamps are given. "Read with care" names a sentence that fails when run on rustc 1.98.0, and says what ran.
If you read only four¶
- The Book, ch. 8.3 — Storing Keys with Associated Values in Hash Maps ↗, in six sections: Creating a New Hash Map ↗, Accessing Values in a Hash Map ↗ (
get,copied,unwrap_or, and the loop "in an arbitrary order"), Managing Ownership in Hash Maps ↗ (aStringkey is moved in; a&strkey is borrowed), Updating a Hash Map ↗ with Overwriting a Value ↗, Adding a Key and Value Only If a Key Isn't Present ↗ (entryandor_insert) and Updating a Value Based on the Old Value ↗ (the word-count loop,*count += 1), then Hashing Functions ↗ (SipHash, and that aBuildHashercan replace it). The chapter is A firstHashMapin the Book's order, without the return values. std::collections::HashMap↗. The opening text is the part to read once: the default hasher isRandomState, chosen to resist HashDoS attacks at some cost in speed, and every key must satisfyEqandHashwith the contractk1 == k2 -> hash(k1) == hash(k2). Then the methods:insert↗ ("If the map did have this key present, the value is updated, and the old value is returned"),get↗,contains_key↗,entry↗,remove↗,iter↗,keys↗ andvalues↗.std::collections— When Should You Use Which Collection? ↗, with Use aHashMapwhen ↗, Use aBTreeMapwhen ↗ and Use theSetvariant of any of theseMaps when ↗. The same page has the Performance ↗ table —HashMapget, insert and remove are O(1)~ expected,BTreeMapO(log n) — an Entries ↗ section on theentryAPI, and a worked count of each character in a string ↗. Its Insert and complex keys ↗ section is the rule behindmutable_key_type: a key must not change in a way that alters its hash or equality while it is in the map.- Programming Rust, 2nd ed. (Blandy, Orendorff & Tindall, O'Reilly 2021), ch. 16 "Collections" → "HashMap
and BTreeMap , with "Entries" and "Map Iteration", then "HashSet" and BTreeSet , with "Set Iteration", "When Equal Values Are Different" and "Whole-Set Operations", then "Hashing" and "Using a Custom Hashing Algorithm". The most complete tour of the two APIs in a book, and the one that treats" entryas a first-class subject rather than a footnote.
Books¶
- Rust in Action (Tim McNamara, Manning 2021), ch. 7 "Files and storage" → "Working with keys and values with HashMap and BTreeMap" (p. 241): "Creating a HashMap and populating it with values", "Retrieving values from HashMap and BTreeMap", "How to decide between HashMap and BTreeMap", and "Adding a database index to actionkv v2.0". A map used for something — the index of a key-value store — rather than shown for its own sake. The library's Rust in Action, run pages check other chapters listing by listing.
- Effective Rust (David Drysdale, O'Reilly 2024), ch. 2 "Traits" → Item 10 "Familiarize yourself with standard traits" → the "PartialEq and Eq" and "Hash" subsections: what deriving each one promises, and why the two must agree — the contract every key on these pages signs. Free online ↗.
- Rust: The Practical Guide (Nouman Azam, Rheinwerk 2025), ch. 5 → §5.5 "HashMaps" and §5.6 "HashSets". Two short sections, the reason A first
HashMapand A firstHashSetexist, and the book's home page here runs every sentence of them. Two to read with care. - Rust for Rustaceans (Jon Gjengset, No Starch 2021) has no section on hash maps —
HashMapappears 22 times in the text, in passing — so it is not on this list; the library's chapter map says what it does cover.
std, the Reference and the crate underneath¶
HashSet↗: "A hash set implemented as aHashMapwhere the value is()", the sentence A firstHashSetleans on, theninsert↗ (returns whether the value was newly inserted),contains↗,remove↗,take↗, and the four operationsunion↗,intersection↗,difference↗ andsymmetric_difference↗.hash_map::Entry↗: the two variants,Occupied↗ andVacant↗, and the methods that close them:or_insert↗,or_insert_with↗,or_default↗ andand_modify↗. The two variant structs,OccupiedEntry↗ andVacantEntry↗, are what the{:?}output on the lesson page shows.hash_map::RandomState↗ (also atstd::hash::RandomState↗): the defaultBuildHasher, seeded from the OS's random source once per thread, which is why five runs print five orders. Thestd::hash↗ module page shows a hand-writtenHashimpl and states theEqcontract.Hash↗ andEq↗: "k1 == k2implieshash(k1) == hash(k2)" on the first, and on the second the three laws — reflexive, symmetric, transitive — thatf64'sNaNbreaks, which is entry 18 of the errors page.Borrow↗: the trait behindget<Q>whereK: Borrow<Q>, withHashMapas its worked example — whyHashMap<String, V>answersget("k")andHashMap<&str, V>refusesget(&some_string)(entry 9). The library'sBorrowlesson runs it.BTreeMap↗ andBTreeSet↗: the ordered pair,Ordinstead ofHash, and therangequery a hash map cannot answer. The lesson here isBTreeMapandBTreeSet.hashbrown↗ (source ↗): the crate whose table has been std'sHashMapsince Rust 1.36, published on its own with a different default hasher. Its README names the design it ports: Google's Swiss Tables ↗, whose design notes explain the control bytes and the SIMD probe. Matt Kulukundis presented that design at CppCon 2017: Designing a Fast, Efficient, Cache-friendly Hash Table, Step by Step ↗ (1 h); the title was checked, the video was not watched here. The general idea, before any of that, is Wikipedia's Hash table ↗.
Rust by Example¶
- Std library types: HashMap ↗:
insert,get,removeanditeron a phone book, withmatchonget. It says a key can be any type that implementsEqandHash, and it prints the map by iterating it — so its shown output is one of the possible orders. - Alternate/custom key types ↗:
#[derive(PartialEq, Eq, Hash)]on a struct key, the fix in entry 17. - HashSet ↗: the four operations, collected and printed.
The error index¶
Each code met on the errors page, with rustc's own long explanation, also printed by rustc --explain:
E0425↗ andE0433↗ — the missinguseE0282↗ — type annotations neededE0308↗ — mismatched types, for anOptionused as its valueE0369↗ — a binary operator with no implementation, forget(k) + 1E0277↗ — a trait bound not satisfied, for&u32 == 5and forBorrowE0507↗ — moving out ofmap[k]E0594↗ andE0596↗ — writing through&, and borrowing&mutfrom a&or a non-mutbindingE0368↗ —+=on a referenceE0382↗ andE0502↗ — the map moved into its loop, and mutated inside itE0599↗ — a method whose bounds the key type does not meetE0597↗ —&strkeys outliving their text
Lints¶
- Clippy's lint list ↗: every lint with its group, level and the version it arrived in; the page's own search box finds
map_entry,iter_over_hash_typeand the rest of the lints page. The levels and groups quoted there were read fromclippy-driver -Whelpon the pinned toolchain rather than from this page, since lints move between groups across releases. - rust-clippy on GitHub ↗: where a lint's source and its discussion live, for the cases the list's one paragraph does not settle — such as why
map_entrystays quiet for&strkeys.
Python, ABAP and Java, for the bridges¶
- Python: dictionaries ↗ and sets ↗ in the tutorial;
dict↗ andset↗ in the library reference;collections.Counter↗ andcollections.defaultdict↗, the two spellings of the counting loop. - ABAP, in the sibling library: Internal tables — three kinds, three promises ↗,
READ TABLEand table expressions ↗, andCOLLECT↗, the statement that isentry().or_insert()with the addition built in. - Java:
java.util.HashMap↗ andjava.util.HashSet↗, whoseputandaddreturn what Rust'sinserts return.
Read with care¶
- Rust: The Practical Guide, §5.5, on
contains_key. "The function returns an Option wrapping the value inside Some if the key exists, and None, otherwise." Run on rustc 1.98.0,word_counts.contains_key("Programming")istrueandtype_name_of_valof it printsbool; the method that returnsOption<&V>isget. Recorded byfirst_hashmap_claims.rs. - Rust: The Practical Guide, §5.5 and §5.6, printing the map and the set. Both sections read their result off
println!("{:?}", word_counts)andprintln!("{:?}", words). The count shown is right; the order is not a property of the program. The book's four-entry map, compiled once and run five times, printed five different orders. Sort, or use aBTreeMap, before reading anything off a printout. - Any page that says "constant time" without "expected". std's own table writes
O(1)~, with the tilde, because a lookup that hits a long probe sequence or a table resize costs more; the average is constant, the worst case is not. The Book's and RBE's pages avoid the claim; the Practical Guide's "extremely fast" is not wrong, just unmeasured, and it is marked not checked on the lesson page.
See also¶
- A first
HashMapand A firstHashSet— the lessons, with every error and lints beside them HashMapandHashSet— the next pages, whose Sources sections this list extendsBTreeMapandBTreeSet— the ordered pair the which collection table sends you toBorrow: look up an owned key with a borrowed one — the std trait above, run- Rust: The Practical Guide, run — the book's home here
- Books — the shelf these four are on
- Returned by value: reading — a reading list of the same shape, for another subject
Po polsku¶
Lista lektur do HashMap i HashSet, sprawdzona 2026-09-23 i ponownie 2026-09-24. Najkrócej: rozdział 8.3 The Book (sześć sekcji, od HashMap::new po funkcje mieszające), strona std::collections::HashMap (uwaga o RandomState i HashDoS, kontrakt Eq i Hash), tabela When Should You Use Which Collection? w std::collections (koszty operacji, sekcja o entry, przykład zliczania znaków) i Programming Rust rozdział 16 „Collections” z sekcjami o HashMap/BTreeMap, wpisach (entries) i HashSet/BTreeSet. Dalej Rust in Action (rozdział 7, mapa jako indeks bazy klucz–wartość), Effective Rust (Item 10: PartialEq/Eq i Hash), strony std dla HashSet, Entry, Borrow, BTreeMap, crate hashbrown i projekt Swiss Tables, na którym się opiera, Rust by Example, indeks błędów dla każdego kodu ze strony błędów i lista lintów clippy.
Czytaj uważnie: Rust: The Practical Guide pisze, że contains_key zwraca Option — na rustc 1.98.0 zwraca bool — i odczytuje wyniki z wydruku {:?} mapy, którego kolejność zmienia się przy każdym uruchomieniu (pięć uruchomień, pięć kolejności). „Stały czas” wyszukiwania to w tabeli std O(1)~, z tyldą: średnio, nie w najgorszym przypadku.
Szukaj po polsku: tablica mieszająca lektury · rust HashMap dokumentacja · rust std collections which collection · hashbrown Swiss Tables · rust HashDoS RandomState · Rust: The Practical Guide HashMap