Skip to the workspace
Pebellslearn by building
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.

rust / Vectors, HashMaps and HashSets

Explore each scene at your own pace.

01 · The rule

The rule

Vectors, HashMaps and HashSets

A 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.

Choose a growable sequence, key-value store or membership set for the access pattern.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.