MARY.WIN

RUSTY — BEGINNER — B04

Vec and HashMap: arrays, collections and
lookups

Give the PHP array's two jobs, the ordered list and the lookup by name, a Rust type each, and read from both without guessing.
Lesson 4 of 9 in Rust beginner track. Before you start: Lessons 2 and 3.

You have two PHP arrays open. $tasks is a list of titles, in the order you added them, and $stock is a count for each item name. Then a typo asks for $tasks[9], and there are two tasks. PHP prints a warning, and it hands you null, and the program carries on to the next line.

Rust splits those two jobs between two types: Vec for the list and HashMap for the lookup. It also gives you two ways to ask for something that might not be there. One of them stops the program. The other hands you None and lets you decide.

This lesson covers four things: Vec<T> for ordered lists, the iterator chain of map, filter and collect, HashMap<K, V> for lookups by key, and arrays with the slices that borrow from them. For each you'll see what it holds, how to read from it, and one trap. Taking apart the Option that get returns is Lesson 7, and iterators get a fuller treatment in Tutorial 10 of the main series. It assumes Lessons 2 and 3. You don't have to memorize the methods here. You can look them up.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/b04_collections.rs)

// Lesson b04: Vec and HashMap.
use std::collections::HashMap;

fn main() {
    // Vec: a growable list of one type.
    let mut tasks: Vec<String> = Vec::new();
    tasks.push("Run tests".to_string());
    tasks.push("Clear cache".to_string());
    println!("count = {}", tasks.len());
    println!("first = {}", tasks[0]);
    println!("tenth = {:?}", tasks.get(9));
    println!("second = {:?}", tasks.get(1));

    for (i, task) in tasks.iter().enumerate() {
        println!("{}: {task}", i + 1);
    }

    // A pipeline looks like Laravel collections: map, filter, collect.
    let lengths: Vec<usize> = tasks.iter().map(|t| t.len()).collect();
    let long: Vec<&String> = tasks.iter().filter(|t| t.len() > 9).collect();
    println!("lengths = {lengths:?}");
    println!("long = {long:?}");

    // HashMap: keys and values, each of one type.
    let mut stock: HashMap<&str, u32> = HashMap::new();
    stock.insert("keyboard", 4);
    stock.insert("mouse", 0);
    println!("keyboard = {:?}", stock.get("keyboard"));
    println!("monitor = {:?}", stock.get("monitor"));

    // `entry` is "update it, or create it first".
    *stock.entry("mouse").or_insert(0) += 10;
    *stock.entry("monitor").or_insert(0) += 1;

    // HashMap order is not stable, so sort the keys before printing.
    let mut keys: Vec<&&str> = stock.keys().collect();
    keys.sort();
    for key in keys {
        println!("{key} -> {}", stock[*key]);
    }
}

Run it from the examples folder:

TERMINAL
cargo run --quiet --bin b04_collections
count = 2
first = Run tests
tenth = None
second = Some("Clear cache")
1: Run tests
2: Clear cache
lengths = [9, 11]
long = ["Clear cache"]
keyboard = Some(4)
monitor = None
keyboard -> 4
monitor -> 1
mouse -> 10

A list in order

A PHP array value can be any type. The list job in Example 1 is narrower: titles in the order you added them, all of them text. Rust gives that job its own type, Vec<T>, a growable list that stores elements of one type next to each other in memory.

Lines 6 to 8 declare tasks as a Vec<String> and push two titles onto the end. Line 10 reads with square brackets, tasks[0], and gets Run tests. Lines 11 and 12 read with get instead: position 9 gives None, and position 1 gives Some("Clear cache"). Those two come from Option<T>, the standard enum for a value that may be absent.¹

What happens past the end?

The program in b04_index_panic.rs announced its plans before it carried them out. It held a vector with one title in it, Run tests, and it worked out a position from the length, tasks.len() + 4, which came to 5. It printed about to read position 5, the way someone reads a recipe step aloud before opening the cupboard. Then it reached for tasks[position] on line 6, and the program ended there.

In PHP, reading a missing key is a warning, not an error, and the null you get travels on to whatever line uses it next. Square brackets on a Rust Vec have no such middle ground. Take a look at Example 2, the program from that scene.

Example 2. Reading past the end (examples/src/bin/b04_index_panic.rs)

// Lesson b04: indexing past the end is a panic, not a null.
fn main() {
    let tasks = vec!["Run tests".to_string()];
    let position = tasks.len() + 4;
    println!("about to read position {position}");
    println!("{}", tasks[position]);
}

Line 3 uses vec! to build a Vec with one title already in it, and line 6 indexes it with square brackets. Run it:

TERMINAL
cargo run --quiet --bin b04_index_panic
about to read position 5

That is all of standard output. Standard error gets the panic: the place, src/bin/b04_index_panic.rs:6:25, and the reason, index out of bounds: the len is 1 but the index is 5. The exit code is 101. A panic is Rust's response to an unrecoverable error: the program prints a message and stops.

So, a question before you read on. The index comes from a user's query string. Which do you write, tasks[index] or tasks.get(index)? The second, and then you handle None.

The iterator chain

In Laravel you'd write collect($tasks)->map(...). In Rust the chain starts with an iterator, which produces a sequence of items, one each time its next method is called.

On line 19, tasks.iter() produces shared references to the titles, so tasks keeps them. map applies a closure, an anonymous function written with vertical bars around its parameters, |t| t.len(). len() counts bytes, and these titles are plain ASCII, so the lengths are 9 and 11.² The annotation Vec<usize> tells collect what to build; usize is the integer type for lengths.

On line 20, filter keeps the items whose closure returns true, here titles longer than nine bytes. Which title passes? Only Clear cache, as a reference rather than a copy, which is why long is a Vec<&String>.

map and filter are lazy: they do nothing until a consuming method like collect asks for items. If you write tasks.iter().map(|t| t.len()); and stop, what happens? Nothing. No lengths are computed.

A lookup by name

Now the lookup job, $stock['mouse'] in PHP. Rust's type for it is HashMap<K, V>, which stores values by key, with one type for all the keys and one for all the values. Line 25 makes stock a HashMap<&str, u32>. Unlike Vec, it needs line 2, use std::collections::HashMap;, which lets the file name it without its full path.

Lines 28 and 29 read with get and return the same kind of Option: Some(4) for keyboard, None for monitor. Line 32 changes a count. stock.entry("mouse").or_insert(0) puts a zero in the slot if the slot is missing and hands back a mutable reference to the count; * reaches through it, and += 10 takes mouse from 0 to 10.

Does stock.get("monitor") add monitor to the map? The output says no. Line 29 prints monitor = None, and monitor -> 1 appears only after line 33 has run. Only entry with or_insert adds it.

Lines 36 to 40 sort before they print, because a HashMap that is asked for its keys will hand over every one of them and will do it, in the standard library's own description, in arbitrary order, which for three keys could be any of six orders, so the example collects the keys, sorts them, and prints keyboard, monitor, mouse. The type on line 36, Vec<&&str>, looks like a typo. It isn't, and you can read past it for now. When you want key order built in, BTreeMap stores and iterates in key order.

Arrays and slices

Some lists never change length. A pixel has three colour channels, and for that Rust has the array, [u32; 3]. Its length is fixed at compile time and is part of its type. A slice, &[u32], borrows a run of elements without owning them, so one function can read arrays and Vecs alike. Can you call push on [1, 2, 3]? No. Its length is part of its type.

Which read do you want?

So every read in Example 1 has an answer, and the read in Example 2 has an ending. The tidy rule is get for an index that comes from outside. But b04_index_panic.rs computed its own index from tasks.len() and was off by four. Square brackets say a missing item is unrecoverable. Is it, in your application? When a list has nothing at the position someone asked for, do you want the program to stop, or a None to handle on the next line? Who should decide, the code or the request?

Testing

The main claim is that the two reads behave differently, and the two runs show it. Run b04_index_panic and check that standard output is the one line about to read position 5 and the exit code is 101, not 0. Then find tenth = None on line 3 of Example 1's output: the same question asked with get, after which the program printed ten more lines. For the map, monitor = None on output line 10 and monitor -> 1 on line 12 sit either side of source line 33, the only line that writes monitor.

Then find one array in your own PHP code and decide its job: list or lookup. That decision is the Rust type. You can start every list as a Vec and change it later.

TL;DR

PHP uses one array for two jobs. Rust gives the ordered list Vec<T> and the lookup by key HashMap<K, V>. Square brackets on a Vec panic past the end; get returns an Option, Some or None. iter, map and filter build a lazy chain that collect runs into the type you annotate. get on a HashMap doesn't insert, entry with or_insert does, and a HashMap visits entries in arbitrary order, so sort before you print. Arrays have a fixed length in their type, and slices borrow from arrays and Vecs alike. Next is Lesson 5, structs.

¹ Option and Vec are in the prelude, the set of names Rust brings into every program automatically, so Example 1 needs no use line for either. HashMap is not, which is why line 2 is there.

² len() counts bytes, as PHP's strlen does. For plain ASCII text, bytes and characters come out the same. Lesson 2 has a word where they don't, café.

The sources.

Programs, their output and the compiler's messages were recorded on rustc 1.100.0 on 2026-11-30. Book locators are to The Rust Programming Language (3rd edition), Programming Rust (3rd edition) and Learn Rust in a Month of Lunches.

SOURCES — 1
  • [S20] Rust Book ch. 8.1 "Storing Lists of Values with Vectors", ch. 8.3 "Storing Keys with Associated Values in Hash Maps", ch. 13.1 "Closures", ch. 13.2 "Iterators"; [S24] std docs for Vec, HashMap, BTreeMap, slice; [S42] Laravel Collections; [S27] PHP Manual "Arrays"; [S48] the recorded demo output. Books: [S17] TRPL ch. 8, Vectors > Reading Elements of Vectors 18.6; ch. 13, Iterators > The Iterator Trait and the next Method 23.8 and Processing a Series of Items with Iterators 23.8; ch. 12, Reading the Argument Values; ch. 8, Hash Maps > Creating a New Hash Map, Adding a Key and Value Only If a Key Isn't Present, Accessing Values 18.8; ch. 3, Data Types > The Array Type 13.7. [S18] PR ch. 3, Characters and Strings in Memory; ch. 16, Collections > Overview. [S19] LRML 1.3.

Rust Book: vectors · Rust Book: hash maps · Rust Book: closures · Rust Book: iterators · Vec documentation · HashMap documentation · BTreeMap documentation · slice documentation · Laravel Collections · PHP arrays

NOT CHECKED — 4
  • The Laravel collect($tasks)->map(...) call in the text was not run. Comparing Laravel collections with Rust iterators is this course's own comparison.
  • The description of usize as the integer type for lengths is not tied to a specific cited passage.
  • Book chapter locators were checked once against the three books and were not re-read for this draft.
  • The PHP warning text was recorded on PHP 8.5 only, and the Rust output and panic message on rustc 1.100.0 only.