Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Language Basics  ›  Capstone Project

Vectors, HashMaps and HashSets

Vector 15 minA Vec is a growable list, a HashMap links keys to values for fast lookup, and a HashSet keeps unique values, all from the standard library.

Vectors, HashMaps and HashSets

Arrays have a fixed length, but the library does not: books arrive, get returned, and new members join every day. For data that grows, Rust's standard library gives you three workhorses. Choosing the right one is most of the job.

The rule

Order → Vec; lookup by key → HashMap; no duplicates → HashSet.

Vec<T>: a growable list of one type, in order.

let mut returned: Vec<String> = Vec::new();
returned.push(String::from("Iron Tides"));
let also = vec![3, 1, 4];            // the vec! macro
let first = &returned[0];             // panics if empty
let maybe = returned.get(5);          // None, no panic

HashMap<K, V>: keys linked to values, looked up quickly by key.

use std::collections::HashMap;

let mut copies: HashMap<String, u32> = HashMap::new();
copies.insert(String::from("Iron Tides"), 3);
*copies.entry(String::from("Night Garden")).or_insert(0) += 1;

match copies.get("Iron Tides") {
    Some(n) => println!("{n} copies"),
    None => println!("not stocked"),
}

insert on an existing key replaces its value. entry(...).or_insert(0) means "the value if it exists, otherwise start it at 0", which is the standard way to count things. A HashMap has no stable order: never rely on the order you iterate it in.

HashSet<T>: unique values only. Inserting a value that is already there changes nothing, and insert returns false to tell you.

use std::collections::HashSet;

let mut borrowers: HashSet<u32> = HashSet::new();
borrowers.insert(1042);
borrowers.insert(1042);          // ignored, returns false
println!("{}", borrowers.len()); // 1

HashMap and HashSet need use std::collections::...; Vec is always in scope.

The shortcut

Describe the data out loud and listen for the key word: "in order" → Vec, "for each X, the Y" → HashMap, "which ones, once each" → HashSet.

Counting loans per titleStep 1 of 4
  1. Say it

    "For each title, the number of loans." That is "for each X, the Y": a HashMap<String, u32>.

The trap is map["key"] or vec[i] on data that might be missing. Both panic; get returns an Option you can handle.

Drills

Answer fast — trust the rule.

quick drill

Which collection fits "the titles returned today, in the order they came back"?

quick drill

What does borrowers.len() print after inserting 1042 twice into a HashSet<u32>?

quick drill

What does copies.get("Missing Book") return when the key is absent?

quick drill

A map has "Iron Tides" => 3. What does copies.insert(String::from("Iron Tides"), 5) do?

Remember

  • Vec keeps order and grows; HashMap finds by key; HashSet keeps each value once.
  • Listen for "in order", "for each X, the Y", "once each".
  • Trap: indexing can panic and hash collections have no order; use get, and sort a Vec when order matters.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainChoose the collection

The library needs (a) the queue of titles returned today in arrival order, (b) the number of copies for each title, and (c) the set of card numbers that borrowed anything this week, with no repeats. Explain which collection fits each, and how you read a count from the map safely.