Rust Playbook

Course › Week 2 · Errors, collections, traits › Day 2 · lesson 9 of 42 · 20 min reading + 60–90 min practice

Vec, String and HashMap

The three collections you will use every day, and the entry API.

VecString&strHashMapentry API

On this page
  1. 1. Vec: a list that can grow
  2. 2. Looping over a Vec: borrow, change, or consume
  3. 3. Why you cannot push while you hold a reference
  4. 4. String, once more
  5. 5. HashMap: keys to values
  6. 6. The entry API: insert or update in one step
  7. 7. Sorting
  8. Coming from PHP
  9. Practice
  10. Remember

A PHP array is three things at once: a list, a map, and an ordered map. Rust splits them into separate types. Today covers the two you will use most, Vec (a list) and HashMap (a map), plus String again, now with the methods you need to take text apart.

All three own their contents on the heap, so everything from Day 3 and Day 4 applies: they move on assignment, and they are lent with & and &mut.

1. Vec: a list that can grow

A Vec<T> holds any number of values of one type T, in order. vec![…] creates one with values in it.

src/main.rs
fn main() {
    let mut long_stays: Vec<u32> = Vec::new();
    for nights in [3, 7, 2, 14, 9] {
        if nights >= 7 {
            long_stays.push(nights);
        }
    }

    let mut guests = vec![2, 4, 1];
    guests.push(3);

    println!("{long_stays:?} has {} items", long_stays.len());
    println!("{guests:?}");
}
$ cargo run
[7, 14, 9] has 3 items
[2, 4, 1, 3]

Unlike an array ([u32; 3], Day 2), a Vec has no fixed length. It is what you use whenever you collect things whose number you do not know in advance: lines, rows, results.

get returns an Option; [i] can panic

v[i] assumes the position exists and panics if it does not. v.get(i) returns an Option, so a missing position is a value you handle:

src/main.rs
fn guest_counts() -> Vec<u32> {
    vec![2, 4, 1] // in a real tool: read from a file or a database
}

fn main() {
    let guests = guest_counts();

    match guests.get(5) {
        Some(count) => println!("booking 5 has {count} guests"),
        None => println!("there is no booking 5"),
    }

    println!("booking 0 has {} guests", guests[0]);
}
$ cargo run
there is no booking 5
booking 0 has 2 guests

Use [i] only where the position cannot be missing, like [0] right after checking the Vec is not empty. Everywhere else, get.

2. Looping over a Vec: borrow, change, or consume

The for loop follows the ownership rules. &v borrows each item, &mut v lets you change each item, and plain v moves the Vec into the loop, after which it is gone.

src/main.rs
fn main() {
    let mut prices: Vec<u64> = vec![15_010, 18_000, 15_010];

    for price in &mut prices {
        *price += 500; // a 500-cent tourist tax on every night
    }

    let mut total: u64 = 0;
    for price in &prices {
        total += price;
    }

    println!("{prices:?}, total {total}");
}
$ cargo run
[15510, 18500, 15510], total 49520

price inside the first loop is a &mut u64: a reference, not the number. *price means “the value the reference points to”, so *price += 500 changes the item in the Vec. In the second loop, total += price works without * because adding a &u64 to a u64 is allowed; changing through a reference is where you need it.

3. Why you cannot push while you hold a reference

This looks harmless, and it is the most common borrow error with collections:

src/main.rsdoes not compile
fn main() {
    let mut lines = vec![String::from("first line")];

    let first = &lines[0];
    lines.push(String::from("second line"));

    println!("{first}");
}
cargo build
error[E0502]: cannot borrow `lines` as mutable because it is also borrowed as immutable
 --> src/main.rs:5:5
  |
4 |     let first = &lines[0];
  |                  ----- immutable borrow occurs here
5 |     lines.push(String::from("second line"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
6 |
7 |     println!("{first}");
  |                ----- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `hello` (bin "hello") due to 1 previous error

It is Day 4’s rule, and here is the real danger it prevents: when a Vec is full, push moves all its items to a bigger block of memory. first would then point to the old, freed block. In C that is a crash that appears only sometimes. In Rust it does not compile.

4. String, once more

Building text

push_str appends to a String you own. format! builds a new String from pieces, like sprintf; it borrows its arguments and moves none of them.

src/main.rs
fn main() {
    let level = "ERROR";
    let message = String::from("Payment failed");

    let mut line = String::from("[2026-11-30 09:41:03] ");
    line.push_str("production.");
    line.push_str(level);

    let full = format!("{line}: {message}");
    println!("{full}");
    println!("{message} is still usable");
}
$ cargo run
[2026-11-30 09:41:03] production.ERROR: Payment failed
Payment failed is still usable

No s[0]

Because text is UTF-8 and a character can be several bytes (Day 4), Rust does not let you index a string by number at all:

src/main.rsdoes not compile
fn main() {
    let city = String::from("Ærøskøbing");
    let first = city[0];
    println!("{first}");
}
cargo build
error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> src/main.rs:3:22
  |
3 |     let first = city[0];
  |                      ^ string indices are ranges of `usize`
  |
  = help: the trait `SliceIndex<str>` is not implemented for `{integer}`
  = note: you can use `.chars().nth()` or `.bytes().nth()`
          for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
help: `usize` implements trait `SliceIndex<T>`
 --> /rustc/20ddd01716a87c0fcf06ae4752d85a4abc15bcdf/library/core/src/slice/index.rs:179:0
  |
  = note: `SliceIndex<[T]>`
 --> /rustc/20ddd01716a87c0fcf06ae4752d85a4abc15bcdf/library/core/src/bstr/traits.rs:201:0
  |
  = note: `SliceIndex<ByteStr>`
  = note: required for `String` to implement `Index<{integer}>`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `hello` (bin "hello") due to 1 previous error

The useful lines are the first one and the note: under it; the lines about SliceIndex describe the standard library’s internals and can be skipped. Say what you mean instead: city.chars().next() for the first character (an Option<char>), or a slice &city[0..n] when you know the byte positions, as with a log timestamp.

Taking a line apart

These methods return slices of the original, so they copy nothing. split_once is the one you will use most: it splits at the first match and returns both halves, or None if there is no match.

src/main.rs
fn main() {
    let line = "  [2026-11-30 09:41:03] production.ERROR: Payment failed {\"booking\":5521}  ";
    let line = line.trim();

    let Some((head, message)) = line.split_once(": ") else {
        println!("not an entry");
        return;
    };

    println!("head:    {head}");
    println!("message: {message}");
    println!("starts with a bracket: {}", line.starts_with('['));
    println!("words in head: {}", head.split(' ').count());
}
$ cargo run
head:    [2026-11-30 09:41:03] production.ERROR
message: Payment failed {"booking":5521}
starts with a bracket: true
words in head: 3

split_once returns Option<(&str, &str)>: an optional pair. let Some((head, message)) = … takes the pair apart into two names, which is how for (name, count) in rows worked on Day 6.

\" inside a Rust string is a quote character, the same escape as in PHP.

5. HashMap: keys to values

A HashMap<K, V> maps keys of one type to values of another, like a PHP array with string keys. It is not imported by default, so it needs a use.

src/main.rs
use std::collections::HashMap;

fn main() {
    let mut rates: HashMap<String, u64> = HashMap::new();
    rates.insert(String::from("Nyhavn flat"), 15_010);
    rates.insert(String::from("Aarhus loft"), 12_500);

    match rates.get("Nyhavn flat") {
        Some(cents) => println!("Nyhavn flat: {cents} cents"),
        None => println!("no rate"),
    }

    println!("has Odense: {}", rates.contains_key("Odense"));
    println!("{} properties", rates.len());
}
$ cargo run
Nyhavn flat: 15010 cents
has Odense: false
2 properties

The map owns its keys, so they are Strings, and insert moves them in. But get takes a &str: you do not need to build a String just to look something up.

get returns an Option, the same way Vec::get does. In PHP, a missing key gives a warning and null.

A HashMap has no order

A PHP array remembers the order you inserted keys in. A Rust HashMap does not, and loops over it in an order that can change from one run to the next. When the order matters, sort the entries (section 7), or use BTreeMap from the same module, which keeps its keys sorted.

6. The entry API: insert or update in one step

Counting is the job you will do most with a map. entry(key) finds the slot for a key, .or_insert(0) fills it with 0 if it was empty, and both together hand you a &mut u64 to the value, which * lets you change.

src/main.rs
use std::collections::BTreeMap;

fn main() {
    let messages = [
        "Payment failed",
        "Deadlock found",
        "Payment failed",
        "cURL error 28",
        "Payment failed",
    ];

    let mut counts: BTreeMap<&str, u64> = BTreeMap::new();
    for message in messages {
        *counts.entry(message).or_insert(0) += 1;
    }

    for (message, count) in &counts {
        println!("{count} × {message}");
    }
}
$ cargo run
1 × Deadlock found
3 × Payment failed
1 × cURL error 28

This is PHP’s $counts[$m] = ($counts[$m] ?? 0) + 1;, with one lookup instead of two.

BTreeMap here only so the printed order is the same every run (alphabetical). The keys are &str because they borrow from messages; a map can hold references as long as what they point to lives longer than the map.

7. Sorting

Numbers sort with sort()

src/main.rs
fn main() {
    let mut nights = vec![7, 2, 14, 3];
    nights.sort();
    println!("{nights:?}");
}
$ cargo run
[2, 3, 7, 14]

Sorting pairs by count

To find the most frequent messages, move the map’s pairs into a Vec and sort it by the count, largest first. sort_by takes a closure: a small inline function, written |a, b| …. Closures get their own day in Week 3; for now read the line as “compare two pairs by their count, b before a”.

src/main.rs
use std::collections::HashMap;

fn main() {
    let messages = [
        "Payment failed",
        "Deadlock found",
        "Payment failed",
        "cURL error 28",
        "Payment failed",
        "cURL error 28",
    ];

    let mut counts: HashMap<&str, u64> = HashMap::new();
    for message in messages {
        *counts.entry(message).or_insert(0) += 1;
    }

    let mut ranked: Vec<(&str, u64)> = Vec::new();
    for (message, count) in counts {
        ranked.push((message, count));
    }
    ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));

    for (message, count) in &ranked {
        println!("{count} × {message}");
    }
}
$ cargo run
3 × Payment failed
2 × cURL error 28
1 × Deadlock found

a.1 is the second item of the pair a, the count; a.0 is the first, the message. cmp compares two values, and .then(…) breaks ties alphabetically, so equal counts always come out in the same order, whatever order the HashMap gave them in.

for (message, count) in counts consumes the map, which is fine: it is not needed after.

Coming from PHP

One PHP array does what three Rust types do:

PHPRust
$list = [2, 4, 1]; $list[] = 3;let mut list = vec![2, 4, 1]; list.push(3);
$list[5] ?? nulllist.get(5): an Option
$map = ['a' => 1]; (keeps insertion order)HashMap (no order) or BTreeMap (sorted by key)
$map['a'] ?? nullmap.get("a"): an Option
$c[$k] = ($c[$k] ?? 0) + 1;*c.entry(k).or_insert(0) += 1;
usort($rows, fn($a, $b) => $b[1] <=> $a[1]);rows.sort_by(|a, b| b.1.cmp(&a.1));
explode(': ', $line, 2)line.split_once(": "): an Option of a pair

The pattern behind every row: where PHP returns null or false for “not there”, Rust returns an Option, and you cannot forget to look.

PracticeThe Book ch. 8, Rustlings strings and hashmaps

Read chapter 8 of the Book.

In Rustlings: 09_strings, 11_hashmaps, then quiz2.

Exercise: errors per hour

Given log lines, count the ERROR entries per hour and print them in time order: 09:00 2. Use split_once to find the level, slice the hour from the timestamp (bytes 12 to 14), and a BTreeMap<&str, u64> keyed by the hour.

Show the solution
src/main.rs
use std::collections::BTreeMap;

fn main() {
    let lines = [
        "[2026-11-30 09:14:27] production.WARNING: Stripe webhook retried",
        "[2026-11-30 09:41:03] production.ERROR: Deadlock found",
        "#0 /var/www/app/Actions/ConfirmBooking.php(41)",
        "[2026-11-30 09:58:10] production.ERROR: Payment failed",
        "[2026-11-30 11:30:12] production.ERROR: cURL error 28",
    ];

    let mut per_hour: BTreeMap<&str, u64> = BTreeMap::new();
    for line in lines {
        let Some((head, _message)) = line.split_once(": ") else {
            continue; // not an entry
        };
        if !line.starts_with('[') || !head.ends_with(".ERROR") {
            continue;
        }
        let hour = &line[12..14];
        *per_hour.entry(hour).or_insert(0) += 1;
    }

    for (hour, count) in &per_hour {
        println!("{hour}:00  {count}");
    }
}
$ cargo run
09:00  2
11:00  1

continue skips to the next line, the same as in PHP. _message starts with an underscore to say “named for clarity, deliberately unused”, which keeps the compiler from warning about it.

Remember

  • Vec for lists, HashMap for lookups, BTreeMap when the order of keys matters.
  • Every “maybe missing” lookup returns an Option: get, split_once, find.
  • Count with *map.entry(key).or_insert(0) += 1.

Tomorrow: Result and the ? operator, so logstat can return errors instead of calling exit from deep inside.