Modeling Data · 14 min · free lesson

Collections

Vec, String, and HashMap own growable data with different trade-offs.

Core idea

entry().or_insert() gives you a mutable reference either way.

Coming from Node.js? Objects and Map vs HashMap covers this side by side.

Start with the idea

Choosing a collection is part of the model, not an afterthought: order, uniqueness, and key access all change what your code can promise. Each of these owns its data, so passing one around follows exactly the same ownership rules as any other value.

Read the code

use std::collections::HashMap;
let text = "rust crab rust";
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in text.split_whitespace() {
    *counts.entry(word).or_insert(0) += 1;
}
assert_eq!(counts.get("rust"), Some(&2));
assert_eq!(counts.get("crab"), Some(&1));
let mut rows: Vec<_> = counts.iter().collect();
rows.sort_unstable_by_key(|(word, _)| **word);
for (word, count) in rows { println!("{word}: {count}"); }

The complete program counts three tokens into two keys, then sorts rows for stable output: crab 1, rust 2.

Practice starter

use std::collections::HashMap;
let text = "red blue red";
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in text.split_whitespace() {
    // TODO: use entry(word).or_insert(0) and increment the stored value.
    let _ = word;
}
println!("{:?}", counts.get("red"));

Practise this code in Playground ↗

An ordered growing Vec, key-value HashMap, and text String have distinct storage shapes.
Pick a collection by the operations and guarantees you need: order, key lookup, or UTF-8 text.

Work through it

Choose a collection by the operations the program promises. Vec<T> preserves an ordered sequence and supports indexed access; appending is a natural operation. HashMap<K, V> associates keys with values and is useful for lookup or counting, but its iteration order is not a stable presentation order. A String owns UTF-8 text rather than an arbitrary sequence of characters. Naming the data structure early keeps later code from relying on an accidental property, such as hash iteration looking sorted in one run.

The entry API handles the common "insert if missing, then update" operation in one lookup. counts.entry(word).or_insert(0) returns a mutable reference to the existing count or to a newly inserted zero. Dereferencing it lets the code increment the stored value. Separate get and insert operations can repeat lookup work. Some nested method-call forms compile under modern Rust borrowing rules; do not assume they always cause a borrow error. The useful distinction is that entry directly expresses one keyed slot and returns mutable access to its stored value. Read the type of the returned reference to see why *count += 1 is needed.

For practice, count words in a short sentence with one repeated word. Print the count for a known key and use get to handle an unknown key safely. Then sort the keys before displaying all counts if predictable output matters. Consider ownership as well: keys borrowed from a longer-lived input can be &str; keys assembled while parsing may need owned String values. The collection's shape, lookup behavior, and ownership together define the data model.

Pick a collection from the operations you need. Vec<T> keeps an ordered, growable sequence and is good for iteration and indexing. HashMap<K, V> associates keys with values and supports expected fast lookup, with hashing and memory overhead. String owns UTF-8 text and can grow. They all own their elements or bytes, so borrowing an element is different from removing or moving it.

Start with a list of names. If you need to preserve their order and print every name, use a vector. If you need to find one name by a unique ID repeatedly, consider a map. Add a duplicate key to a map and observe whether insertion replaces an earlier value. Then inspect the return type of get: it may be absent, and a returned reference remains tied to the collection. Choose the data structure after writing down required operations, expected input size, and whether order matters.

Try it

Count repeated words in a BTreeMap with owned keys. Keep case as supplied; empty input produces an empty map. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

Why is entry() better here?

Reveal the answer
  1. It avoids hashing the key at all
  2. It looks the key up once instead of twice
  3. It keeps the map sorted by insertion order

entry looks the key up once, exposes the occupied or vacant slot, and returns mutable access to its value. It still hashes the key, and it does not sort the map.

One more experiment

Add one more crab to text, then predict the two assert_eq! values and the printed rows. Finally remove the sort_unstable_by_key line and explain why the printed order is no longer promised.

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Collections (courseId "basics", lessonId "collections")
Link: https://crabrix.com/learn/basics/collections/
Goal: entry().or_insert() gives you a mutable reference either way.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/collections) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.