Skip to main content

IndexRustTutorial

Rust Collections, Iterators and Strings for JS Devs

Part 8 of Rust for web developers: Vec, HashMap, HashSet and BTreeMap, lazy iterator chains that read like array methods, and practical string handling.

By LearnWebCraft Team23 min readBeginner

Part 8 of 15 · Rust for web developers

A lot of backend code is moving data around in lists and maps. You fetch rows, filter them, group them by something, sort them, pick the first twenty and turn them into JSON. In JavaScript you do that with arrays, objects, Map and Set, and a chain of filter, map and reduce.

Rust has the same tools with different names, and one big difference in how they work. Rust's iterator methods look almost exactly like JavaScript's array methods, but they're lazy. A chain of filter and map doesn't build intermediate arrays. Nothing happens until something at the end asks for the results, and then each item flows through the whole chain one at a time. The compiler turns the chain into a loop as tight as one you'd write by hand.

This part covers the collections you'll use in web code, then iterators in depth, then a return to strings with the practical splitting and parsing you need for things like headers and query strings. As usual, every output below comes from a real run on Rust 1.100.0. If you missed it, part 7 covered the closures and traits that iterators are built from.

Vec: the growable list

Vec<T> is Rust's version of a JavaScript array: an ordered list that can grow and shrink. Unlike a JavaScript array, every element has the same type.

Fig. 1rustRun
let mut tags: Vec<&str> = Vec::new();
tags.push("rust");
tags.push("web");
tags.extend(["axum", "tokio", "web"]);
println!("tags: {tags:?} len={}", tags.len());

tags.insert(0, "backend");
let last = tags.pop();
println!("after insert and pop: {tags:?}, popped {last:?}");

let removed = tags.remove(1);
println!("removed {removed:?}, now {tags:?}");
Fig. 2text
tags: ["rust", "web", "axum", "tokio", "web"] len=5
after insert and pop: ["backend", "rust", "web", "axum", "tokio"], popped Some("web")
removed "rust", now ["backend", "web", "axum", "tokio"]

pop returns an Option, because the vector might be empty. remove(i) returns the element directly and panics if i is out of range. insert(0, ...) and remove(1) shift every later element, so they're slow on long vectors, just like unshift and splice in JavaScript.

Looking things up:

Fig. 3rust
println!("contains axum? {}", tags.contains(&"axum"));
println!("first {:?}, last {:?}, get(10) {:?}", tags.first(), tags.last(), tags.get(10));
Fig. 4text
contains axum? true
first Some("backend"), last Some("tokio"), get(10) None

tags[10] would panic. tags.get(10) returns None. In request handlers, where the index might come from user input, use get.

Sorting and cleaning up:

Fig. 5rustRun
let mut nums = vec![5, 3, 8, 3, 1, 8, 8];
nums.sort();
nums.dedup();
println!("sorted and deduped: {nums:?}");
println!("binary_search 5: {:?}, 4: {:?}", nums.binary_search(&5), nums.binary_search(&4));

nums.retain(|n| n % 2 == 1);
println!("odd only: {nums:?}");
Fig. 6text
sorted and deduped: [1, 3, 5, 8]
binary_search 5: Ok(2), 4: Err(2)
odd only: [1, 3, 5]

A few things differ from JavaScript here. sort() sorts numbers numerically. JavaScript's [10, 9, 1].sort() sorts them as strings and gives [1, 10, 9], which has surprised everyone at least once. dedup() only removes consecutive duplicates, so sort first. binary_search returns Err(position) when the item is missing, telling you where it would go. And retain is an in-place filter, which changes the vector instead of making a new one.

windows and chunks are two I reach for often:

Fig. 7rustRun
let readings = [3, 5, 4, 9, 2];
let pairs: Vec<_> = readings.windows(2).map(|w| w[1] - w[0]).collect();
println!("differences: {pairs:?}");
for chunk in readings.chunks(2) {
    println!("chunk {chunk:?}");
}
Fig. 8text
differences: [2, -1, 5, -7]
chunk [3, 5]
chunk [4, 9]
chunk [2]

windows(2) gives every overlapping pair, which is perfect for differences between readings or detecting changes. chunks(2) splits into groups, the last one possibly shorter. That's batching, which comes up constantly when inserting rows into a database in groups of a hundred.

Capacity

A Vec has a length and a capacity. When it runs out of capacity, it allocates a bigger buffer and copies everything over, as we saw in part 3. If you know roughly how many items are coming, you can allocate once:

Fig. 9rustRun
let mut v = Vec::with_capacity(10);
println!("len {} capacity {}", v.len(), v.capacity());
v.extend(0..3);
println!("len {} capacity {}", v.len(), v.capacity());
Fig. 10text
len 0 capacity 10
len 3 capacity 10

This is an optimisation, not something you need to think about most of the time. collect() already does it for you when the iterator knows its size.

HashMap: key-value storage

HashMap<K, V> is Rust's Map. Every key has the same type, and every value has the same type.

Fig. 11rustRun
use std::collections::HashMap;

let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 3);
stock.insert("pear".to_string(), 0);
let old = stock.insert("apple".to_string(), 5);
println!("insert returned the old value: {old:?}");

println!("apple: {:?}, kiwi: {:?}", stock.get("apple"), stock.get("kiwi"));
println!("has pear? {}", stock.contains_key("pear"));
Fig. 12text
insert returned the old value: Some(3)
apple: Some(5), kiwi: None
has pear? true

insert returns the previous value, if there was one. get returns an Option, never undefined. And notice stock.get("apple") with a &str, even though the keys are String. Rust lets you look up a String key with a &str, so you don't have to allocate a new string just to search.

The entry API

The most useful HashMap feature has no direct JavaScript equivalent. You've used it since part 1 for counting words:

Fig. 13rust
*stock.entry("kiwi".to_string()).or_insert(0) += 4;
*stock.entry("apple".to_string()).or_insert(0) += 1;
stock.entry("fig".to_string()).or_default();
if let Some(n) = stock.get_mut("pear") {
    *n += 2;
}

entry(key) looks up the slot for a key once. or_insert(0) fills it with 0 if it was empty and returns a mutable reference to the value, which *... += 1 then updates. or_default() does the same with the type's default value. In JavaScript you'd write map.set(k, (map.get(k) ?? 0) + 1), which looks the key up twice. The entry API does it once and makes "insert if missing, then update" a single expression.

get_mut gives you a mutable reference to an existing value, for when you only want to update keys that are already there.

Iteration order

Iterating a HashMap gives you keys in an order that's effectively random, and it can change between runs. Rust's default hasher is seeded randomly to protect against hash-flooding attacks, where an attacker sends request parameters chosen to collide and slow your server down. That's a good default for web code, but it means you have to sort when you want a stable order:

Fig. 14rust
let mut keys: Vec<_> = stock.keys().collect();
keys.sort();
println!("keys sorted: {keys:?}");
Fig. 15text
keys sorted: ["apple", "kiwi", "pear"]

If you always want sorted keys, use a BTreeMap instead, which keeps its keys in order:

Fig. 16rust
use std::collections::BTreeMap;

let sorted: BTreeMap<_, _> = stock.iter().collect();
println!("BTreeMap keeps order: {sorted:?}");
Fig. 17text
BTreeMap keeps order: {"apple": 6, "kiwi": 4, "pear": 2}

BTreeMap is slightly slower than HashMap for single lookups, but it supports range queries ("all keys between a and m"), and its output order is predictable. That makes it the better choice whenever the map ends up in JSON responses or test snapshots, where a shuffled key order would make the output change between runs.

HashSet and VecDeque

A HashSet<T> is a set of unique values, like JavaScript's Set, but with the set operations JavaScript only recently started adding:

Fig. 18rustRun
use std::collections::HashSet;

let backend: HashSet<&str> = ["rust", "go", "node", "python"].into_iter().collect();
let typed: HashSet<&str> = ["rust", "go", "typescript"].into_iter().collect();
let mut both: Vec<_> = backend.intersection(&typed).collect();
both.sort();
let mut only_backend: Vec<_> = backend.difference(&typed).collect();
only_backend.sort();
println!("in both: {both:?}, backend only: {only_backend:?}");
Fig. 19text
in both: ["go", "rust"], backend only: ["node", "python"]

insert returns false if the value was already there, which makes duplicate detection a one-liner:

Fig. 20rust
let mut seen = HashSet::new();
for id in [4, 7, 4, 9, 7] {
    if !seen.insert(id) {
        println!("duplicate id {id}");
    }
}
Fig. 21text
duplicate id 4
duplicate id 7

A VecDeque<T> is a double-ended queue: fast to add and remove at both ends, which a Vec is not. Use it for work queues:

Fig. 22rust
let mut queue: VecDeque<&str> = VecDeque::new();
queue.push_back("job-1");
queue.push_back("job-2");
queue.push_front("urgent");
while let Some(job) = queue.pop_front() {
    println!("processing {job}");
}
Fig. 23text
processing urgent
processing job-1
processing job-2

while let is the loop version of if let: keep going while the pattern matches. It's the natural way to drain a queue.

Which collection to use

You need Use JavaScript
An ordered list Vec<T> Array
A fixed-size list [T; N] Array
Lookup by key HashMap<K, V> Map or an object
Lookup by key, sorted output BTreeMap<K, V> Map plus sorting
Unique values HashSet<T> Set
Unique values, sorted BTreeSet<T> Set plus sorting
A queue VecDeque<T> Array with shift (slow)
A priority queue BinaryHeap<T> A library

In practice, Vec and HashMap cover nearly everything. The Rust standard library docs give the same advice.

Iterators

The basic chain

Here's some data like you might get from a database query:

Fig. 24rust
#[derive(Debug, Clone)]
struct User {
    name: &'static str,
    role: &'static str,
    active: bool,
    spent_cents: u64,
}

let users = vec![
    User { name: "ana", role: "admin", active: true, spent_cents: 12_500 },
    User { name: "bo", role: "member", active: false, spent_cents: 3_000 },
    User { name: "cy", role: "member", active: true, spent_cents: 48_000 },
    User { name: "di", role: "editor", active: true, spent_cents: 0 },
    User { name: "ed", role: "member", active: true, spent_cents: 9_900 },
];

The names of active users:

Fig. 25rust
let active_names: Vec<&str> = users.iter().filter(|u| u.active).map(|u| u.name).collect();
Fig. 26text
active: ["ana", "cy", "di", "ed"]

In JavaScript: users.filter(u => u.active).map(u => u.name). The Rust version has two extra steps: .iter() at the start, and .collect() at the end. Both are there for the same reason. A Vec is a collection, not an iterator. .iter() creates an iterator over it, the iterator methods transform that iterator, and .collect() gathers the results into a new collection. Forget .iter() and the compiler tells you:

Fig. 27text
error[E0599]: no method named `map` found for struct `Vec<{integer}>` in the current scope
 --> src/bin/e_vecmap.rs:3:26
  |
3 |     let doubled = prices.map(|p| p * 2);
  |                          ^^^ `Vec<{integer}>` is not an iterator
  |
help: call `.into_iter()` first

Iterators are lazy

This is the key difference. In JavaScript, filter builds a whole new array, then map builds another one. In Rust, filter and map build nothing. They return a new iterator that remembers what to do. The work happens only when something pulls items through, one at a time.

You can watch it:

Fig. 28rustRun
let lazy = (1..=3).map(|n| {
    println!("  mapping {n}");
    n * 10
});
println!("nothing mapped yet");
let first_big = lazy.filter(|n| *n > 15).next();
println!("first over 15: {first_big:?}");
Fig. 29text
nothing mapped yet
  mapping 1
  mapping 2
first over 15: Some(20)

"nothing mapped yet" prints first, because creating lazy did nothing. Then .next() asks for one item that passes the filter. The iterator maps 1 (10, too small), maps 2 (20, passes), and stops. 3 is never mapped at all.

That has real consequences. A chain over a million rows that ends in .take(10) only processes as many rows as it needs to find ten. No intermediate Vec is ever allocated. And because everything is generic and known at compile time, the optimiser can fuse the whole chain into a single loop. The Rust book's chapter on iterators shows benchmarks where the iterator version is as fast as the hand-written loop.

The flip side: an iterator you never consume does nothing at all. The compiler warns you:

Fig. 30rust
names.iter().map(|n| println!("hello {n}"));
Fig. 31text
warning: unused `Map` that must be used
 --> src/bin/e_lazy.rs:3:5
  |
3 |     names.iter().map(|n| println!("hello {n}"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: iterators are lazy and do nothing unless consumed

It also suggests for_each, which is the method for running a side effect on each item. A plain for loop is usually clearer, though.

collect needs to know what to build

collect can build many kinds of collection: a Vec, a HashMap, a HashSet, a String, even a Result<Vec<_>, _> as we saw in part 5. So it needs to be told which:

Fig. 32text
error[E0283]: type annotations needed
 --> src/bin/e_collect.rs:3:9
  |
3 |     let upper = names.iter().map(|n| n.to_uppercase()).collect();
  |         ^^^^^                                          ------- type must be known at this point
  |
help: consider giving `upper` an explicit type
  |
3 |     let upper: Vec<_> = names.iter().map(|n| n.to_uppercase()).collect();
  |              ++++++++

Vec<_> means "a Vec of whatever the items are". You can also use the turbofish: .collect::<Vec<_>>().

iter, iter_mut and into_iter

There are three ways to get an iterator from a collection, and they match the three kinds of access from part 3:

Method Items are Collection afterwards
.iter() &T, shared references Unchanged, still usable
.iter_mut() &mut T, mutable references Changed in place, still usable
.into_iter() T, owned values Gone, moved into the iterator
Fig. 33rustRun
let mut prices = vec![100, 250, 75];
prices.iter_mut().for_each(|p| *p += 5);
println!("iter_mut: {prices:?}");
let owned: Vec<String> = prices.into_iter().map(|p| format!("${p}")).collect();
println!("into_iter: {owned:?}");
Fig. 34text
iter_mut: [105, 255, 80]
into_iter: ["$105", "$255", "$80"]

After into_iter, prices can't be used. That's the same move you saw with for name in names in part 3, because a for loop calls into_iter for you. for x in &v calls .iter(), and for x in &mut v calls .iter_mut().

Use iter() by default. Use into_iter() when you're done with the collection and want to move its contents somewhere else without cloning.

The methods you'll use most

With the users from above:

Fig. 35rust
let total: u64 = users.iter().map(|u| u.spent_cents).sum();
println!("members: {}", users.iter().filter(|u| u.role == "member").count());
println!("any admin? {}", users.iter().any(|u| u.role == "admin"));
println!("all spent something? {}", users.iter().all(|u| u.spent_cents > 0));
println!("find cy: {:?}", users.iter().find(|u| u.name == "cy").map(|u| u.role));
println!("position of di: {:?}", users.iter().position(|u| u.name == "di"));

let top = users.iter().max_by_key(|u| u.spent_cents).unwrap();
Fig. 36text
total spent: 73400
members: 3
any admin? true
all spent something? false
find cy: Some("member")
position of di: Some(3)
top spender: cy (48000)

find and position return Option, where JavaScript's find returns undefined and findIndex returns -1. max_by_key returns an Option too, because the iterator might be empty. The unwrap is fine here only because we know the list isn't empty.

Grouping, which JavaScript only recently got as Object.groupBy, is a loop with the entry API:

Fig. 37rust
let mut by_role: HashMap<&str, Vec<&str>> = HashMap::new();
for u in &users {
    by_role.entry(u.role).or_default().push(u.name);
}
Fig. 38text
by role: [("admin", ["ana"]), ("editor", ["di"]), ("member", ["bo", "cy", "ed"])]

(I sorted the result before printing, for a stable order.) Splitting in two by a condition:

Fig. 39rust
let (paying, free): (Vec<&User>, Vec<&User>) = users.iter().partition(|u| u.spent_cents > 0);
Fig. 40text
paying 4, free 1

Building a string from pieces, with take, skip and enumerate:

Fig. 41rust
let csv = users
    .iter()
    .take(3)
    .map(|u| format!("{},{}", u.name, u.spent_cents))
    .collect::<Vec<_>>()
    .join("\n");

let labelled: Vec<String> = users
    .iter()
    .skip(3)
    .enumerate()
    .map(|(i, u)| format!("{}:{}", i + 4, u.name))
    .collect();
Fig. 42text
ana,12500
bo,3000
cy,48000
["4:di", "5:ed"]

Combining iterators:

Fig. 43rust
let ids = [101, 102, 103];
let names = ["ana", "bo", "cy"];
let pairs: Vec<(i32, &str)> = ids.into_iter().zip(names).collect();
let lookup: HashMap<i32, &str> = ids.into_iter().zip(names).collect();

let tags = vec![vec!["rust", "web"], vec!["axum"], vec![]];
let flat: Vec<&str> = tags.into_iter().flatten().collect();
let chars: Vec<char> = ["ab", "cd"].iter().flat_map(|s| s.chars()).collect();
let chained: Vec<i32> = (1..=3).chain(7..=8).rev().collect();
let product = (1..=5).fold(1, |acc, n| acc * n);
let parsed: Vec<u32> = ["1", "x", "3"].iter().filter_map(|s| s.parse().ok()).collect();
Fig. 44text
zip: [(101, "ana"), (102, "bo"), (103, "cy")]
as map, 102 is Some("bo")
flatten: ["rust", "web", "axum"]
flat_map: ['a', 'b', 'c', 'd']
chain + rev: [8, 7, 3, 2, 1]
fold product: 120
filter_map: [1, 3]

Notice that collecting pairs into a HashMap builds a map directly, which is the equivalent of Object.fromEntries or new Map(pairs). And filter_map combines filtering and mapping when the mapping might fail: here it keeps only the strings that parse.

Rust iterators and JavaScript array methods

JavaScript Rust
arr.map(f) iter.map(f)
arr.filter(f) iter.filter(f)
arr.reduce(f, init) iter.fold(init, f)
arr.forEach(f) for x in ... or iter.for_each(f)
arr.find(f) (or undefined) iter.find(f) (Option)
arr.findIndex(f) (or -1) iter.position(f) (Option)
arr.some(f), arr.every(f) iter.any(f), iter.all(f)
arr.length after a filter iter.count()
arr.slice(0, n) iter.take(n)
arr.slice(n) iter.skip(n)
arr.flat(), arr.flatMap(f) iter.flatten(), iter.flat_map(f)
arr.entries() iter.enumerate()
arr.concat(other) iter.chain(other)
[...arr].reverse() iter.rev()
arr.join(",") vec.join(",") on strings
Math.max(...arr.map(f)) iter.map(f).max()
Object.groupBy(arr, f) A loop with entry().or_default()
Object.fromEntries(pairs) pairs.collect::<HashMap<_, _>>()
Eager, builds arrays at each step Lazy, one pass, no intermediate allocations

Writing your own iterator

Any type can become an iterator by implementing the Iterator trait, which needs only one method, next:

Fig. 45rust
struct Countdown {
    from: u32,
}

impl Iterator for Countdown {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.from == 0 {
            None
        } else {
            self.from -= 1;
            Some(self.from + 1)
        }
    }
}

type Item = u32; is an associated type: it says what the iterator yields. next returns Some(item) until it's done, then None. That's the whole protocol, and it's the same idea as JavaScript's iterator protocol with { value, done }.

Implement next, and you get every other method for free:

Fig. 46rust
let countdown: Vec<u32> = Countdown { from: 3 }.collect();
let evens: u32 = Countdown { from: 10 }.filter(|n| n % 2 == 0).sum();
Fig. 47text
countdown: [3, 2, 1]
even sum from countdown: 30

That's default methods from part 7 at work. The Iterator trait has over 70 provided methods, all built on top of your one next. In web code you'd write one of these to page through an API or a database cursor, yielding one row at a time.

Strings, revisited

We covered String and &str in part 2. Now that you know iterators and closures, here's the practical string handling that comes up in web code.

Characters and bytes, one more time

Fig. 48rustRun
let word = "naïve";
println!("bytes {} chars {}", word.len(), word.chars().count());
for (i, c) in word.char_indices() {
    print!("{i}:{c} ");
}
Fig. 49text
bytes 6 chars 5
0:n 1:a 2:ï 4:v 5:e

char_indices gives each character with its byte position. The jump from 2 to 4 is the two-byte ï. When you need to slice a string at a character, this is how you find safe byte positions.

Splitting

Parsing a header:

Fig. 50rustRun
let header = "Content-Type: text/html; charset=utf-8";
if let Some((name, value)) = header.split_once(':') {
    println!("name={name:?} value={:?}", value.trim());
}
Fig. 51text
name="Content-Type" value="text/html; charset=utf-8"

split_once splits at the first occurrence and returns both halves as an Option, None if the separator isn't there. It's the right tool for key: value, key=value and user@host.

The other split variants:

Fig. 52rust
let parts: Vec<&str> = "a,b,,c".split(',').collect();
let parts: Vec<&str> = "a,b,,c".split(',').filter(|s| !s.is_empty()).collect();
let parts: Vec<&str> = "  many   spaces here ".split_whitespace().collect();
let parts: Vec<&str> = "k=v=w".splitn(2, '=').collect();
Fig. 53text
split: ["a", "b", "", "c"]
split no empties: ["a", "b", "c"]
split_whitespace: ["many", "spaces", "here"]
splitn: ["k", "v=w"]

Note that split returns an iterator, not a Vec. Every one of these results is borrowed from the original string, so splitting allocates nothing until you collect.

Putting split, filter_map and split_once together, here's a query string parser in one expression:

Fig. 54rust
let query = "page=2&sort=name&q=rust";
let pairs: Vec<(&str, &str)> = query.split('&').filter_map(|kv| kv.split_once('=')).collect();
Fig. 55text
query: [("page", "2"), ("sort", "name"), ("q", "rust")]

(A real one also needs percent-decoding. Axum's Query extractor does all of that for you in part 10, but it's good to know there's no magic involved.)

Building strings

A URL slug from a title, using chars, filter, collect into a String, and join:

Fig. 56rust
let title = "Hello, World! Rust 2024";
let slug: String = title
    .chars()
    .filter(|c| c.is_alphanumeric() || c.is_whitespace())
    .collect::<String>()
    .to_lowercase()
    .split_whitespace()
    .collect::<Vec<_>>()
    .join("-");
Fig. 57text
slug: hello-world-rust-2024

A preview cut safely by characters, not bytes:

Fig. 58rust
let preview: String = "café au lait, s'il vous plaît".chars().take(8).collect();
Fig. 59text
preview: café au ...

Building up HTML or any text with push_str, starting with enough capacity:

Fig. 60rust
let mut html = String::with_capacity(64);
for item in ["one", "two"] {
    html.push_str("<li>");
    html.push_str(item);
    html.push_str("</li>");
}
Fig. 61text
<li>one</li><li>two</li>

(Please don't build HTML from user input like this in real code. Use a templating crate that escapes for you. It's fine here because the items are fixed.)

Formatting

The format specifiers you'll actually use:

Fig. 62rustRun
println!("[{:<8}] [{:>8}] [{:^8}] [{:08.3}]", "left", "right", "mid", 3.14159);
println!("{:?} {:?}", "tab\there", 'q');
Fig. 63text
[left    ] [   right] [  mid   ] [0003.142]
"tab\there" 'q'

<, > and ^ align left, right and centre within a width. 08.3 means "8 wide, padded with zeros, 3 decimal places". {:?} on a string shows quotes and escapes, which is very useful for debugging whitespace problems.

to_string, to_owned and String::from

You'll see three ways to make a String from a &str, and they all do the same thing:

Fig. 64rust
let s1 = "owned".to_string();
let s2 = "owned".to_owned();
let s3 = String::from("owned");

to_string comes from Display, so it works on anything printable, including numbers. to_owned comes from a trait for turning any borrowed thing into its owned version. String::from comes from From. Pick one and be consistent. I use to_string for most things and String::from for literals.

Back to wordfreq

Two changes this time. First, count_words gets rewritten as an iterator chain. Second, a --skip-common flag that leaves out words like "the" and "is", using a HashSet.

The common words are a constant array:

Fig. 65rust
/// Words that are rarely interesting on their own.
pub const COMMON_WORDS: [&str; 12] = [
    "a", "an", "and", "are", "in", "is", "it", "of", "on", "the", "to", "was",
];

The counting function, rewritten:

Fig. 66rust
/// Count each word in `text`, ignoring case and surrounding punctuation.
pub fn count_words(text: &str) -> HashMap<String, usize> {
    count_words_skipping(text, &HashSet::new())
}

/// Like [`count_words`], but leaves out every word in `skip`.
pub fn count_words_skipping(text: &str, skip: &HashSet<&str>) -> HashMap<String, usize> {
    text.split_whitespace()
        .map(normalise)
        .filter(|word| !word.is_empty() && !skip.contains(word.as_str()))
        .fold(HashMap::new(), |mut counts, word| {
            *counts.entry(word).or_insert(0) += 1;
            counts
        })
}

Read it top to bottom: split into raw words, normalise each one, drop the empty ones and the skipped ones, and fold them into a map of counts. .map(normalise) passes the function by name, since it already takes a &str and returns a String. skip.contains(word.as_str()) checks the set without allocating. The fold starts with an empty map, and for each word, bumps its count and passes the map on.

Is the iterator version better than the loop? It's about the same length. I find it reads more clearly, because each step says what it does, and there's no mutable state outside the chain. But a for loop is not wrong in Rust, and when an iterator chain gets long or needs early returns, a loop is often clearer. Use whichever reads better.

count_words keeps its old signature and calls the new function with an empty set, so nothing else needed changing, including the tests.

longest_word in report.rs shrinks to one chain:

Fig. 67rust
fn longest_word(counts: &HashMap<String, usize>) -> &str {
    counts
        .keys()
        .min_by(|a, b| char_len(b).cmp(&char_len(a)).then(a.cmp(b)))
        .map(String::as_str)
        .unwrap_or("")
}

This one is a bit of a puzzle, so let's walk through it. We want the longest word, with ties going to the alphabetically first. min_by returns the smallest item according to a comparison. The comparison puts longer words first, by comparing b to a instead of a to b, then breaks ties alphabetically. So the "smallest" by that ordering is the longest word, and the alphabetically first among equals. The part 2 test, longest_word_prefers_alphabetical_on_ties, still passes, which is exactly what it was written for.

.map(String::as_str) converts Option<&String> to Option<&str>. .unwrap_or("") handles an empty map.

In main.rs, the flag:

Fig. 68rust
/// Leave out common words like "the" and "is"
#[arg(long)]
skip_common: bool,

A bool field in clap becomes a flag that takes no value. And the counting:

Fig. 69rust
let skip: HashSet<&str> = if cli.skip_common {
    COMMON_WORDS.into_iter().collect()
} else {
    HashSet::new()
};
let counts = count_words_skipping(&text, &skip);

The difference it makes:

Fig. 70bash
cargo run -q -- notes.txt --skip-common
Fig. 71text
3 lines, 27 words, 16 unique
longest word: compiler (8 chars)
9.0 words per line

 1. cargo        3 ###
 2. compiler     2 ##
 3. rust         2 ##
 4. builds       1 #
 5. code         1 #

Without the flag, "is", "the" and "and" took three of the top five places. Now the list shows what the text is actually about. (The summary line still counts every word, since the report is built from the full text. Whether it should is a judgement call, and exercise 1.)

A new test:

Fig. 72rustRun
#[test]
fn skipping_leaves_words_out() {
    let skip: HashSet<&str> = COMMON_WORDS.into_iter().collect();
    let counts = count_words_skipping("The cat and the hat", &skip);
    let mut words: Vec<&String> = counts.keys().collect();
    words.sort();
    assert_eq!(words, ["cat", "hat"]);
}

All tests pass, clippy and rustfmt are clean:

Fig. 73text
test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Exercises

  1. Make --skip-common also affect the summary line, so "unique" counts only the words that are left. Where's the cleanest place to make that change?
  2. Add a --skip-file words.txt option that reads extra words to skip from a file, one per line. Combine them with COMMON_WORDS using chain.
  3. Using the users list, write a single iterator chain that returns the names of active members, sorted by how much they spent, highest first.
  4. Write a struct Pages iterator that yields page numbers 1..=n for a given total and page size, so Pages::new(45, 20) yields 1, 2, 3. Then use .map to turn each into a URL like /posts?page=2.
  5. Write fn parse_cookie(header: &str) -> HashMap<&str, &str> for headers like "theme=dark; lang=en; id=42". Which split methods did you use? What happens with a cookie that has no =?

Next up: async Rust and Tokio

That's the end of the language fundamentals that don't involve concurrency. You can now model data with structs and enums, handle errors without exceptions, organise code into crates, write generic code with traits, and process collections with iterators.

The last piece before we start on the web server is async. A web server spends most of its time waiting: for requests, for the database, for other APIs. Part 9 covers how Rust handles waiting without blocking: async and await, futures, the Tokio runtime, spawning tasks, and how all of it differs from JavaScript's promises and event loop. There are some real surprises in there for JavaScript developers, starting with the fact that a Rust future does nothing at all until you await it, a lot like the lazy iterators you've just seen.