Sub topic 2
Rust Vectors and Hash Maps: Storing and Looking Up Collections of Data
Assume you know Rust ownership, borrowing, Option, match, and how to run a Cargo program.
Common `Vec` methods
A Vec<T> stores elements of one type in order. These methods change a mutable vector:
fn main() {
let mut v = vec![5, 3, 8, 3, 1];
v.insert(0, 2);
let removed = v.remove(1);
v.sort();
v.dedup();
v.retain(|&x| x > 2);
println!("{removed} {v:?}");
}insert and remove shift later elements, so they can be slower for large vectors. sort orders the elements. dedup removes adjacent duplicates, so sort first when you want to remove all duplicates. retain keeps only elements for which its closure returns true.
Borrowing part of a `Vec` as a slice
A slice, written &[T], is a borrowed view into consecutive elements. It does not own the data. Functions that accept slices can work with a whole vector, part of one, or an array.
fn largest(items: &[i32]) -> Option<&i32> {
items.iter().max()
}
fn main() {
let values = vec![4, 9, 2, 7];
println!("{:?}", largest(&values[1..3]));
}Storing different kinds of values with an enum
A vector has one element type. An enum can represent several kinds of values under one type:
#[derive(Debug)]
enum Cell {
Int(i32),
Text(String),
}
fn main() {
let row = vec![Cell::Int(3), Cell::Text(String::from("blue"))];
for cell in &row {
match cell {
Cell::Int(n) => println!("number {n}"),
Cell::Text(s) => println!("text {s}"),
}
}
}Length, capacity, and reallocation
len is the number of elements. capacity is the space currently reserved. When a push exceeds capacity, Rust allocates a larger buffer and moves the elements.
fn main() {
let mut values = Vec::with_capacity(10);
println!("{} {}", values.len(), values.capacity());
for n in 0..10 {
values.push(n);
}
}A reference into a vector becomes invalid if reallocation could occur, so Rust rejects a push while such a reference is alive.
Creating and using a `HashMap`
A HashMap<K, V> stores values by key. Lookup does not depend on insertion order.
use std::collections::HashMap;
fn main() {
let mut stock = HashMap::new();
stock.insert("apple", 3);
println!("{:?}", stock.get("apple"));
println!("{:?}", stock.remove("apple"));
}get and remove return Option, because the key might be absent.
Ownership in a `HashMap`
Inserting an owned String moves the key and value into the map. Borrow them first if you still need them afterward. Copy types such as integers remain usable.
use std::collections::HashMap;
fn main() {
let key = String::from("color");
let value = String::from("green");
let mut map = HashMap::new();
map.insert(key, value);
// key and value cannot be used here.
}Exercise
Why might retain be preferable to repeatedly calling remove?
Show answer
It expresses the filtering rule directly and avoids manually tracking shifting indexes.