MARY.WIN

RUSTY — DESIGN PATTERNS — 07

Strategy:
the third type parameter of HashMap

Pattern 7 of 12 · In the life of one value: carries a choice.
Part of Rust design patterns.

Learning question: How does a collection let you replace one of its algorithms without knowing which one you will pick?

HashMap<K, V> has a third type parameter that you can leave unwritten. This article reads what it is, the trait it must implement, and what changes when you supply your own.

Scope. We read library/std/src/collections/hash/map.rs and library/core/src/hash/mod.rs at Rust 1.100.0 [S3]. We do not cover how hash tables resolve collisions, and we do not recommend a hasher. You need traits at the level of "a set of methods a type promises", and generics at the level of Vec<T>. The pattern's parts are named as in Design Patterns [S1, ch. 5, "Strategy"].

A map with a settled view of its own order

Example 1 puts four entries in a map and prints the keys. It was run three times.

Example 1. Compiles; run three times (compile-fail/run07_strategy_order.rs, first half)

let default: HashMap<&str, u32> =
    HashMap::from([("bolts", 40), ("nuts", 12), ("washers", 7), ("rivets", 3)]);
println!("RandomState:        {:?}", default.keys().collect::<Vec<_>>());

The map held four keys and printed them in an order. A snapshot test had written that order down and believed in it the way a hen believes in the fence. The map was built again by the same code from the same four pairs. It printed them in a different order, and then, on the third run, in another.

OUTPUT
RandomState:        ["nuts", "rivets", "washers", "bolts"]
RandomState:        ["washers", "bolts", "rivets", "nuts"]
RandomState:        ["bolts", "washers", "nuts", "rivets"]

Predict

Nothing in Example 1 is random on its face. Before reading on: the output label is a hint. Where could a per-run difference be coming from, and where would you expect to be able to turn it off?

Name the parts

Role in the pattern [S1] In std Where [S3]
Context HashMap<K, V, S> map.rs line 245
Strategy trait BuildHasher, which produces a Hasher core/src/hash/mod.rs lines 637 and 312
ConcreteStrategy (the default) RandomState named as the default at map.rs line 248
ConcreteStrategy (yours) any type implementing BuildHasher your code

What is S?

A collection that hard-codes its hash function makes one choice for every caller. Thankfully, HashMap takes the function as a parameter. Take a look at Example 2.

Example 2. The context and the strategy (library/std/src/collections/hash/map.rs lines 245 to 252; library/core/src/hash/mod.rs lines 637 to 656, attributes and doc comments removed; the trait's provided method hash_one, line 695, is not shown [S3])

pub struct HashMap<K, V, S = RandomState, A: Allocator = Global> {
    base: base::HashMap<K, V, S, A>,
}

pub trait BuildHasher {
    type Hasher: Hasher;
    fn build_hasher(&self) -> Self::Hasher;
}

The fourth parameter, A, is the allocator; it carries an unstable attribute at line 249 and this article reads past it. There are two new pieces. S = RandomState is a default type parameter: write HashMap<K, V> and you get RandomState without asking. And BuildHasher is a trait with one required method, which hands back a fresh Hasher each time the map needs to hash a key. The documentation on the struct explains the scene: the default algorithm is randomly seeded, and was selected to resist HashDoS attacks [S3, map.rs lines 17 to 18]. That seed is the per-run difference, and S is where you turn it off.

HashMap and the hasher it is configured with: HashMap owns a value of type S, S implements BuildHasher, build_hasher returns a Hasher, and RandomState, BuildHasherDefault and BuildConstant are three implementations The second half of the same program names a different strategy in the map's type, and builds the map with HashMap::default() and extend in place of HashMap::from (compile-fail/run07_strategy_order.rs, lines 9 to 11):

let mut fixed: HashMap<&str, u32, BuildHasherDefault<DefaultHasher>> = HashMap::default();
fixed.extend([("bolts", 40), ("nuts", 12), ("washers", 7), ("rivets", 3)]);
println!("BuildHasherDefault: {:?}", fixed.keys().collect::<Vec<_>>());
OUTPUT
BuildHasherDefault: ["washers", "nuts", "rivets", "bolts"]
BuildHasherDefault: ["washers", "nuts", "rivets", "bolts"]
BuildHasherDefault: ["washers", "nuts", "rivets", "bolts"]

The same order three times. The four pairs and the keys() call are the same as in the first half.

What transfers, and what does not

Passing a comparison callable to usort is the PHP habit closest to this: the manual's signature is usort(array &$array, callable $callback), a sort whose comparison the caller supplies [S4]. Injecting an interface is the same arrangement with a named type. The roles transfer whole. What does not transfer is when the choice is made. The book's Context holds a reference to a Strategy object and can be given a different one while the program runs [S1]. Here the strategy is a type parameter, so HashMap<&str, u32, RandomState> and HashMap<&str, u32, BuildHasherDefault<DefaultHasher>> are two different types, the compiler generates code for each [S5], and a function that takes one will not accept the other: rustc 1.100.0 reports E0308, mismatched types (evidence/ev07_strategy_type_mismatch.rs and .stderr, beside this article; not yet in compile-fail/). The Rust patterns book describes Strategy in the same terms as the original, a family of interchangeable algorithms each in its own type [S2, ch. 7, "Strategy pattern"].

Should you have turned it off?

So the order is stable and the snapshot test passes. The fixed order is still not a promised order, since std documents keys as visiting the keys in arbitrary order (map.rs line 487) and says of DefaultHasher that its internal algorithm is not specified and should not be relied upon over releases (library/std/src/hash/random.rs lines 90 to 91), and std's documentation warns, in bold, that a map built with a hasher that does not rely on a random seed is not resistant to HashDoS attacks (map.rs lines 221 to 222), so for a map whose keys come from a request you have replaced a flaky test with an exposure, and the test was arguably the thing that was wrong. Did the test need a different hasher, or a sorted Vec, or a BTreeMap?

Practice tier: judgment. The compiler checks that S implements BuildHasher. Whether a given strategy is a good idea is not something it can see.

Testing

The claim is that the map calls the strategy it was given. Example 3 supplies the worst possible one and counts the calls.

Example 3. A hasher that always answers 7 (tests/p07_strategy_hasher.rs, abridged: lines 15 to 22, not shown, define BuildConstant, whose build_hasher adds one to BUILT and returns a Constant)

struct Constant;
impl Hasher for Constant {
    fn finish(&self) -> u64 { 7 }
    fn write(&mut self, _bytes: &[u8]) {}
}

let mut stock: HashMap<&str, u32, BuildConstant> = HashMap::with_hasher(BuildConstant);
stock.insert("bolts", 40);
stock.insert("nuts", 12);
assert_eq!(stock.get("bolts"), Some(&40));
assert_eq!(stock.get("nuts"), Some(&12));
assert_eq!(stock.get("washers"), None);
assert!(BUILT.load(Ordering::Relaxed) >= 5, "one hasher per insert and lookup");

Every key collides, and the map still answers correctly, because the hash only chooses where to look and equality decides what is found (std requires keys to implement both Eq and Hash, map.rs lines 37 to 38). It passed on rustc 1.100.0. It would fail if the map ignored S.

Retrieve

  1. What does HashMap<K, V> use for S when you do not say?
  2. Why can't you pass a HashMap<K, V, BuildConstant> to a function that takes HashMap<K, V>?

The Adapters article returns to "a trait the caller is written against", with the trait on the other side of the call.

TL;DR

HashMap<K, V, S> is a Strategy context: S is a type implementing BuildHasher, and it defaults to RandomState, which is randomly seeded. Supplying another S changes how keys are hashed; in this article's program the constructor changed with it, and the keys() call did not. Because the strategy is a type parameter, it is chosen at compile time, and maps with different strategies are different types.

The sources.

Each article names its sources in brackets, with the file, chapter or line to look at. Line numbers are for the tag or commit each article names and will move. Each article says which toolchain its tests passed on: rustc 1.100.0 for eleven of them, rustc 1.97.0 on Linux for Adapter.

SOURCES — 7
  • [S1] Gamma, Helm, Johnson, Vlissides, Design Patterns, ch. 5, "Strategy" (Intent, Participants).
  • [S2] Evan Williams, Design Patterns and Best Practices in Rust (Packt, 2026), ch. 7, "Strategy pattern: swappable algorithms".
  • [S3] rust-lang/rust at tag 1.100.0: library/std/src/collections/hash/map.rs, library/core/src/hash/mod.rs, library/std/src/hash/random.rs; line numbers checked against the raw files at that tag on 2026-11-29.
  • [S4] PHP manual, "usort", https://www.php.net/manual/en/function.usort.php, read 2026-11-29.
  • [S5] The Rust Programming Language, ch. 10.1, "Generic Data Types", section "Performance of Code Using Generics" (monomorphization), https://doc.rust-lang.org/book/ch10-01-syntax.html, read 2026-11-29.
  • Program output is from three consecutive runs of one binary built with rustc 1.100.0.
  • The E0308 output in evidence/ is from rustc 1.100.0 (0ef1bc386), edition 2021, run on 2026-11-29.
NOT CHECKED — 3
  • The snapshot test in the opening scene belongs to the scene. No such test exists in the course code.
  • That the map asks for a fresh Hasher each time it hashes a key rests on the test's count and on core/src/hash/mod.rs. The hashing itself is in hashbrown, which was not read.
  • The attributions to *Design Patterns* and to Williams were not checked against the books again for this page.