MARY.WIN

RUSTY — DESIGN PATTERNS — 08

Enums as states:
Entry is occupied or vacant, and never unsure

Pattern 8 of 12 · In the life of one value: in one state at a time.
Part of Rust design patterns.

Learning question: How do you represent "one of these situations, each with its own data and its own operations" so that code cannot mix them up?

Looking up a key and then acting on the result is two steps, and between them a program can lose track of which case it is in. This article reads std::collections::hash_map::Entry, an enum whose two variants are the two cases, to see what each one holds and what each one allows.

Scope. We read library/std/src/collections/hash/map.rs at Rust 1.100.0 [S3]. We do not cover the hashing itself or the lifetime parameter on Entry, which you can read past. You need enums and match. The parts are named against the State pattern in Design Patterns [S1, ch. 5, "State"], with one substitution explained below.

A slot asked for what it does not have

Example 1 looks up a seat and, in the branch for a free seat, asks who is sitting in it.

Example 1. Does not compile (compile-fail/cf08_enum_entry.rs, lines 4 to 7)

let mut seats: HashMap<&str, u32> = HashMap::new();
if let Entry::Vacant(slot) = seats.entry("12A") {
    println!("{}", slot.get());
}

The code had said, one line earlier, that this branch was for a vacant seat. It then asked the vacant seat for its occupant, in the manner of someone knocking on the door of a house he has just been told is empty. It did not regard the two lines as being in any tension. The compiler looked for a get on the thing in hand.

OUTPUT
error[E0599]: no method named `get` found for struct `std::collections::hash_map::VacantEntry<'a, K, V, A>` in the current scope
 --> cf08_enum_entry.rs:6:29
  |
6 |         println!("{}", slot.get());
  |                             ^^^ method not found in `std::collections::hash_map::VacantEntry<'_, &str, u32>`

Predict

Before reading on: a design with one Entry struct and an is_occupied: bool field would have compiled Example 1. What would get() have had to do at run time when the flag was false?

Name the parts

Role in the pattern [S1] In std Where [S3]
Context the HashMap, through entry(&mut self, key) map.rs line 1012
State enum Entry line 1949
ConcreteState OccupiedEntry, VacantEntry lines 1977 and 1999

What are the alternatives?

Sometimes a value has modes, and the fields that make sense in one mode are meaningless in another, so every method starts by checking a flag. Thankfully, an enum lets each mode carry only what belongs to it. Take a look at Example 2.

Example 2. The enum and one method that uses it (library/std/src/collections/hash/map.rs, lines 1949 to 1962 and 2515 to 2520, attributes, lifetime bounds and the allocator parameter removed [S3])

pub enum Entry<'a, K, V> {
    Occupied(OccupiedEntry<'a, K, V>),
    Vacant(VacantEntry<'a, K, V>),
}

pub fn or_insert(self, default: V) -> &'a mut V {
    match self {
        Occupied(entry) => entry.into_mut(),
        Vacant(entry) => entry.insert(default),
    }
}

There are two new pieces. Entry has exactly two variants, and each wraps its own struct: an OccupiedEntry has get, get_mut, insert and remove (lines 2806, 2839, 2891 and 2914); a VacantEntry has insert and key (lines 2975 and 2933), and no get: its impl block, lines 2919 to 3001, defines key, into_key, insert and insert_entry. And or_insert is a match with one arm per variant and no fallback arm. Inside the Occupied arm, entry is an OccupiedEntry and only its methods are in reach. The answer to the prediction is that nothing has to be decided at run time, because the wrong call was never written.

The two things map.entry(key) can be: Occupied with get, get_mut, insert and remove; Vacant with insert and key

What transfers, and what does not

The book's State pattern gives each state its own class behind a common interface, and the context delegates to whichever it currently holds [S1]. The purpose transfers: behaviour that depends on state lives with that state. The mechanism is different enough that I'd flag the mapping as an interpretation. A Rust enum is a closed list known to the compiler; there is no common interface that both variants must implement, and that absence is the point, since get exists on one and not the other. The Rust patterns book treats State as a way to evolve the behaviour of a type in a language without classes [S2, ch. 8, "State pattern"]. PHP enums, available from PHP 8.1 [S4], are the closest thing you have, with one gap: a PHP enum case cannot carry its own data. The manual's words are that enum cases "are forbidden from having state", and that static or object properties are not allowed [S5].

Which states are really different?

So the two cases cannot be confused. It is tempting, having seen this, to turn every boolean into a two-variant enum, and the test for whether that helps is whether the variants hold different data or permit different operations, as Occupied and Vacant do, or whether they are one struct with a label on it, in which case the enum adds a match to every use and removes no mistake that could have been made. Four boolean flags on a task can describe sixteen combinations. How many of the sixteen can happen?

Practice tier: compiler. Exhaustive match and per-variant methods are checked for you. Finding the real alternatives is judgment.

Testing

The claim is that a lookup yields exactly one of the two alternatives, matching the map's contents. Example 3 would fail if a missing key came back Occupied.

Example 3. One lookup, one alternative (tests/p08_enum_entry.rs, first test)

let mut seats: HashMap<&str, u32> = HashMap::new();
match seats.entry("12A") {
    Entry::Vacant(slot) => { slot.insert(1); }
    Entry::Occupied(_) => panic!("nothing was inserted yet"),
}
assert_eq!(seats["12A"], 1);

It passed on rustc 1.100.0, with a second test for the occupied case.

Retrieve

  1. Name one method OccupiedEntry has that VacantEntry does not.
  2. Why does or_insert need no wildcard arm?

Typestate made the opposite choice for the same problem: states as types, checked without a match. Read the two turns side by side.

TL;DR

hash_map::Entry is an enum with two variants, Occupied and Vacant, each wrapping a struct with its own methods. HashMap::entry returns one of them, and a match gives each arm access only to the operations valid in that case. Asking a vacant entry for its value is a compile error, E0599.

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 — 6
  • [S1] Gamma, Helm, Johnson, Vlissides, Design Patterns, ch. 5, "State" (Intent, Participants).
  • [S2] Evan Williams, Design Patterns and Best Practices in Rust (Packt, 2026), ch. 8, "State pattern: changing behavior based on state".
  • [S3] rust-lang/rust at tag 1.100.0: library/std/src/collections/hash/map.rs; line numbers checked against the raw file at that tag on 2026-11-29.
  • [S4] PHP manual, "Enumerations" (header: PHP 8 >= 8.1.0), https://www.php.net/manual/en/language.types.enumerations.php, read 2026-11-29.
  • [S5] PHP manual, "Enumerations: Differences from objects", https://www.php.net/manual/en/language.enumerations.object-differences.php, read 2026-11-29.
  • Compiler output is from rustc 1.100.0, with the trailing summary removed.
NOT CHECKED — 5
  • The design with one Entry struct and a boolean flag, in Predict, is a thought experiment. No code for it was written.
  • or_insert, in Example 2, is not called by any test.
  • That PHP enums are the closest thing PHP has is a judgment. The manual's page on backed enumerations was not read.
  • The method lists name some of each type's methods, not all of them.
  • The attributions to *Design Patterns* and to Williams were not checked against the books again for this page.