Skip to content
RustLearn

Module 09 — Collections & Strings

Goal

Vec, HashMap, HashSet, and the String vs &str split that trips up every newcomer — including what UTF-8 really means for indexing.

Start here — what this module is really about

Three data structures cover the overwhelming majority of everyday Rust, and this module is about them plus the one thing that reliably confuses newcomers: text.

Vec<T> — a growable list. Items of one type, in order, indexed from zero. It is the default choice whenever you need "several of these". Behind the scenes it holds one contiguous block of heap memory and moves to a bigger block when it fills up — a detail that matters, because it explains the borrow errors you met in module 05.

HashMap<K, V> — lookup by key. Store a value under a key and get it back without searching. Keys must be hashable and comparable, and nothing is stored in any predictable order.

HashSet<T> — membership. "Have I seen this before?", answered instantly, with duplicates impossible.

Then, text. Rust has two string types and it is not being awkward:

  • String is owned, growable text. You can add to it, and you are responsible for it.
  • &str (a string slice) is a borrowed view of text that already exists somewhere else.

You met this split in module 05; here it gets real. And there is one more surprise: you cannot index a string by number. s[0] does not compile. That is because Rust strings are UTF-8, where a single visible character may occupy one to four bytes — so "the byte at position 0" and "the first character" are different questions, and Rust makes you say which one you mean. Once you know that, the API stops feeling obstructive and starts looking careful.

The one sentence to remember: Vec for a list, HashMap for lookup, HashSet for membership — and text is UTF-8, so ask for characters or bytes explicitly.

Learning objectives

  • Use Vec<T> fluently, including capacity, ownership, and iteration modes
  • Use HashMap, BTreeMap, HashSet, VecDeque and know when each fits
  • Master the entry API
  • Explain String vs &str and the three ways to view UTF-8 text
  • Avoid the classic indexing and encoding traps

9.1 Vec<T>

A growable, heap-allocated array. Your default sequence type.

rust
let mut v: Vec<i32> = Vec::new();
let mut v = vec![1, 2, 3];              // macro
let mut v = Vec::with_capacity(100);    // pre-allocate, avoids reallocation
let zeros = vec![0u8; 1024];

v.push(4);
let last = v.pop();                     // Option<i32>
v.insert(0, 99);
v.remove(0);                            // O(n): shifts everything left
v.swap_remove(0);                       // O(1): moves the last element into the hole
v.extend([5, 6, 7]);
v.retain(|x| x % 2 == 0);               // keep matching elements, in place
v.dedup();                              // remove CONSECUTIVE duplicates
v.sort();
v.sort_by(|a, b| b.cmp(a));             // descending
v.sort_by_key(|x| x.abs());
v.reverse();
v.clear();
v.truncate(2);
let (a, b) = v.split_at(1);

Access

rust
let third = &v[2];                 // panics if out of bounds
let third = v.get(2);              // Option<&i32> — prefer this for untrusted indexes

match v.get(100) {
    Some(x) => println!("{x}"),
    None => println!("no element"),
}

Capacity vs length

rust
let mut v = Vec::new();
for i in 0..10 {
    v.push(i);
    println!("len={} cap={}", v.len(), v.capacity());
}

Capacity roughly doubles when exceeded. Each growth reallocates and memcpys, which is why with_capacity matters in hot paths and why holding a reference across a push is a borrow error (module 05).

Three ways to iterate

rust
let v = vec![String::from("a"), String::from("b")];

for s in &v { }          // &String     — read only, v still usable
for s in &mut v { }      // &mut String — mutate in place
for s in v { }           // String      — consumes v; v is moved

Equivalently v.iter(), v.iter_mut(), v.into_iter(). Getting this distinction right is most of what people mean by "fighting the borrow checker with collections".

rust
let mut v = vec![1, 2, 3];
for x in &mut v { *x *= 10; }
assert_eq!(v, vec![10, 20, 30]);

Vec of enums — heterogeneous data

rust
enum Cell { Int(i32), Float(f64), Text(String) }

let row = vec![
    Cell::Int(3),
    Cell::Text(String::from("blue")),
    Cell::Float(10.12),
];

A Vec holds one type, but that type can be an enum. This is the standard trick when you need mixed content and know all the cases up front. (When you don't, use Vec<Box<dyn Trait>> — module 12.)


The Vec operations you will actually use

rust
let mut scores: Vec<i32> = Vec::new();
scores.push(10);
scores.push(20);

// Reading: two ways, with very different failure behaviour
let first = scores[0];          // panics if out of range
let maybe = scores.get(0);      // returns Option<&i32> — None if out of range

// Iterating: three forms, three ownership stances
for s in &scores      { }       // borrow each item — the Vec survives
for s in &mut scores  { }       // borrow mutably — you can change items
for s in scores       { }       // consume the Vec — it is gone afterwards

// The everyday methods
scores.len();                   // how many
scores.is_empty();
scores.contains(&10);
scores.pop();                   // Option<i32> — removes and returns the last
scores.sort();

The two things to internalise:

  • [index] versus .get(index) is a real decision. Use [..] when an out-of-range index would mean your logic is broken (a panic is the correct outcome). Use .get(..) when the index comes from outside — user input, a parsed file — and handle the None.
  • for s in scores consumes the vector. This is module 04 again, and it catches everyone once: the loop takes ownership, so the Vec is unusable afterwards. Write &scores unless you genuinely want it consumed. If you did want the items themselves, into_iter() says so explicitly.

Analogy — the expanding filing drawer

An array is a printer's tray with a fixed number of slots, decided when it was made. A Vec is a filing drawer that quietly buys a bigger drawer and moves everything across when it fills up. That move is why pushing to a Vec while holding a reference into it is forbidden: your reference would point at the old drawer, which has just been thrown out.

9.2 HashMap<K, V>

rust
use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Red"), 50);

let blue = scores.get("Blue");             // Option<&i32>
let blue = scores.get("Blue").copied().unwrap_or(0);   // i32

for (team, score) in &scores {             // iteration order is RANDOM
    println!("{team}: {score}");
}

scores.contains_key("Blue");
scores.remove("Blue");                     // Option<V>
scores.len();
scores.keys();  scores.values();  scores.values_mut();

Ownership: insert moves owned keys and values into the map. Copy types are copied.

rust
let name = String::from("key");
map.insert(name, 5);
// println!("{name}");   // ❌ moved

The entry API — learn this

rust
// insert only if absent
scores.entry(String::from("Yellow")).or_insert(50);

// count occurrences — the canonical idiom
let text = "the quick brown fox the lazy dog the end";
let mut counts: HashMap<&str, i32> = HashMap::new();
for word in text.split_whitespace() {
    *counts.entry(word).or_insert(0) += 1;
}

// group items
let mut groups: HashMap<usize, Vec<&str>> = HashMap::new();
for w in text.split_whitespace() {
    groups.entry(w.len()).or_default().push(w);
}

// expensive default computed lazily
map.entry(key).or_insert_with(|| expensive_default());

// modify existing or insert
map.entry(key).and_modify(|v| *v += 1).or_insert(1);

or_insert returns &mut V, which is why *... += 1 works. Doing this with get/insert requires two lookups and usually a borrow-checker fight — entry does one lookup and satisfies the borrow checker by construction.

Map variants

TypeOrderingLookupUse when
HashMaprandomO(1) avgdefault
BTreeMapsorted by keyO(log n)you need ordered iteration or range queries
HashSetrandomO(1) avgmembership testing, dedup
BTreeSetsortedO(log n)ordered unique items
VecDequeinsertionO(1) both endsqueues, ring buffers
BinaryHeapmax firstO(log n) push/poppriority queues
rust
use std::collections::{BTreeMap, HashSet, VecDeque};

let mut m = BTreeMap::new();
m.insert(3, "c"); m.insert(1, "a"); m.insert(2, "b");
for (k, v) in &m { print!("{k}{v} "); }         // 1a 2b 3c — always sorted
for (k, v) in m.range(2..) { }                  // range query

let a: HashSet<i32> = [1, 2, 3].into_iter().collect();
let b: HashSet<i32> = [2, 3, 4].into_iter().collect();
let inter: HashSet<_> = a.intersection(&b).copied().collect();   // {2, 3}
let union: HashSet<_> = a.union(&b).copied().collect();
let diff: HashSet<_> = a.difference(&b).copied().collect();      // {1}

let mut q = VecDeque::new();
q.push_back(1); q.push_front(0);
q.pop_front();                                  // Option<T>

Note on hashing

HashMap's default hasher (SipHash) is DoS-resistant but not the fastest. For internal, non-adversarial data, rustc-hash or ahash can be 2–4× faster. Also, keys must implement Eq + Hash, which f64 does not — so floats can't be keys.


The HashMap idiom that replaces four lines

Counting things is the classic use, and it exposes the one API worth memorising:

rust
use std::collections::HashMap;

let text = "the quick brown the fox the";
let mut counts: HashMap<&str, i32> = HashMap::new();

for word in text.split_whitespace() {
    *counts.entry(word).or_insert(0) += 1;
}

That middle line does a lot, so take it apart:

  1. counts.entry(word) asks "is there a slot for this key?" and hands back an Entry — a handle to that slot, occupied or not.
  2. .or_insert(0) says: if it was empty, put a 0 there first. Either way, hand me a &mut i32 pointing at the value.
  3. *... += 1 follows that mutable reference and increments the number in place.

Written out the long way it is a match on get, an insert in one branch and an update in the other — four or five lines, with a double lookup. The entry API does it once.

Two further notes: get returns an Option<&V>, because the key may be absent — that is module 08 doing its job. And iteration order is not insertion order and may differ between runs; if you need order, sort the keys yourself or use a BTreeMap.

Analogy — the coat check

A HashMap is a coat check: hand over a ticket, get the coat, and it does not matter how many coats there are — the lookup takes the same moment either way. But the tickets must be genuinely distinguishable, which is why keys have to be hashable, and why nothing is ever stored in ticket order.

9.3 Strings

Rust has more string types than most languages because it refuses to hide the cost of encoding and allocation.

TypeOwned?Description
Stringyesgrowable, heap, UTF-8
&strnoborrowed view into UTF-8 bytes ("string slice")
&'static strnoa string literal, baked into the binary
Box<str>yesowned but fixed-size (rare)
Cow<'_, str>maybeborrowed until mutated (avoids allocation)
OsString/Pathyesplatform-native, possibly non-UTF-8

Creating and growing

rust
let s = String::new();
let s = String::from("hello");
let s = "hello".to_string();
let s = "hello".to_owned();
let n = 42.to_string();

let mut s = String::from("foo");
s.push_str("bar");        // append &str
s.push('!');              // append char
let s3 = s + "baz";       // NOTE: `s` is MOVED here (operator+ takes self)

let a = String::from("tic");
let b = String::from("tac");
let joined = format!("{a}-{b}");   // format! borrows; nothing is moved. Prefer this.

The three views of text

Strings cannot be indexed by integer.

rust
let s = String::from("hello");
// let c = s[0];    // ❌ E0277: `String` cannot be indexed by `{integer}`

Why: UTF-8 is variable-width. "héllo" is 6 bytes but 5 characters. s[0] would be ambiguous — byte, scalar value, or grapheme? Rust makes you say which:

rust
let s = "नमस्ते";     // Hindi for "namaste"

s.len();                       // 18 — BYTES
s.chars().count();             // 6  — Unicode scalar values
s.bytes().count();             // 18

for c in s.chars() { print!("{c} "); }      // न म स ् त े
for b in s.bytes() { print!("{b} "); }      // 224 164 168 ...

for (i, c) in s.char_indices() {            // byte offset + char
    println!("{i}: {c}");
}

Note that even chars() isn't "characters" as a human sees them — स् is two scalar values forming one grapheme cluster. For true grapheme iteration use the unicode-segmentation crate.

Slicing uses byte offsets and panics on a non-boundary:

rust
let hello = "Здравствуйте";
let s = &hello[0..4];        // "Зд" — each Cyrillic char is 2 bytes
// let s = &hello[0..1];     // 💥 panics: byte index 1 is not a char boundary

Common operations

rust
let s = "  Hello, World!  ";

s.trim();  s.trim_start();  s.trim_end();
s.to_uppercase();  s.to_lowercase();
s.contains("World");  s.starts_with("  He");  s.ends_with("!  ");
s.replace("World", "Rust");
s.find("World");                        // Option<usize> byte offset
s.split(',').collect::<Vec<_>>();
s.split_whitespace().collect::<Vec<_>>();
s.splitn(2, ',').collect::<Vec<_>>();
s.split_once(',');                      // Option<(&str, &str)>
s.lines();
s.repeat(3);
s.parse::<i32>();                       // Result<i32, ParseIntError>
s.is_empty();
s.chars().rev().collect::<String>();    // reverse (by scalar value)

let words = vec!["a", "b", "c"];
words.join("-");                        // "a-b-c"
words.concat();                         // "abc"

&str vs String in APIs

rust
fn takes_str(s: &str) {}          // ✅ accepts &String, &str, literals, slices
fn takes_string(s: String) {}     // takes ownership — only when you need to store it
fn flexible(s: impl Into<String>) { let s: String = s.into(); }  // convenient constructor

Deref coercion means &String automatically becomes &str at call sites, so &str parameters are strictly more general. Use String parameters only when the function stores the value.


Why s[0] does not compile

rust
let s = String::from("héllo");
// let c = s[0];   // ❌ error[E0277]: `String` cannot be indexed by `{integer}`

Rust strings are UTF-8. In UTF-8 a character takes between one and four bytes: h takes one, é takes two. So the string above is 6 bytes long but 5 characters long, and s.len() returns 6.

Now the question "what is s[0]?" has no single honest answer. The first byte? That might be half a character, which is not a valid character at all. The first character? That would require scanning, so it would be a hidden loop, not the constant-time operation [0] looks like. Rust refuses to guess, and makes you ask precisely:

rust
s.chars().nth(0);          // Option<char> — the first character (scans)
s.bytes().nth(0);          // Option<u8>   — the first byte
&s[0..1];                  // a slice by BYTE range — panics if it splits a character
s.chars().count();         // number of characters (scans)
s.len();                   // number of BYTES (instant)

The practical rules that follow:

  • To go through text, use .chars(). Almost always what you meant.
  • .len() is bytes. For "how long does this look to a human", use .chars().count() — and know that even that is approximate for emoji and combining accents.
  • Slicing by range is by byte offsets, and panics if the boundary lands mid-character. Prefer .chars() or methods like .split_whitespace() that cannot land wrong.

This is one of those places where Rust looks harder than other languages and is actually just being honest — in most languages the same operation silently produces broken text.

Analogy — the letter and the window

String is a letter you own — you can append to it, edit it, and you are responsible for filing it. &str is a window onto some letter that already exists, possibly one printed into the programme itself. Take the window in your function parameters (anyone can lend you one) and hand back the letter when the caller needs to keep it. And because the text is UTF-8, counting characters is reading the letter, not measuring the paper.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
Vec<T>A growable, ordered list of values of one type.
capacityHow much room a Vec has reserved — distinct from len, how much it is using.
reallocationMoving to a bigger block when capacity runs out. Why references into a Vec block mutation.
HashMap<K, V>Lookup of values by key, in no particular order.
HashSet<T>A collection of unique values, for membership tests.
entry APImap.entry(k).or_insert(v) — insert-if-absent then hand back a mutable reference, in one lookup.
StringOwned, growable, heap-allocated UTF-8 text.
&strA borrowed view of UTF-8 text. What literals are, and what functions should take.
UTF-8The encoding Rust strings use: one character is one to four bytes.
charA single Unicode scalar value — always four bytes in memory.
BTreeMapLike HashMap, but keeps keys sorted.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0277]: String cannot be indexed by {integer}You tried s[0] on text.Use .chars().nth(n), or a byte-range slice &s[a..b] if you really mean bytes.
error[E0502]: cannot borrow as mutable ... also borrowed as immutableYou held a reference into a Vec and then pushed to it.Finish with the reference first; the Vec may reallocate and invalidate it.
error[E0382]: borrow of moved value after a for loopfor x in collection consumed it.Iterate over &collection instead.
error[E0308]: expected &str, found String (or the reverse)The owned/borrowed distinction.&my_string or my_string.as_str() to borrow; .to_string() to own.
byte index is not a char boundary (at runtime)A slice range split a multi-byte character.Use .chars(), or find boundaries with .char_indices().

Now make it stick: work through the drills for this module, then carry on to Module 10 — Modules, Crates & Project Layout.