Collections: Vec, HashMap and String
Part 1 · Rust. Store many values with Vec, look things up by key with HashMap, understand String vs &str, and loop over them all with for.
A café doesn’t have one order. It has a queue of them, a whole menu of prices, and a lot of text: names, notes, “extra hot please”. Rust’s standard library gives you collections for this: types that hold many values and can grow while your program runs. In this lesson you’ll meet the three you’ll use most: Vec, HashMap and String.
All three keep their contents on the heap (remember the storage room from the Ownership lesson). That’s what lets them grow and shrink.
Vec: a growable list
A Vec<T> (say “vector”) is a list of values of the same type, in order. Think of the café’s order queue: new orders join at the end, and you can see who’s first, second and third.
fn main() { let mut queue: Vec<String> = Vec::new();
queue.push(String::from("Latte")); queue.push(String::from("Mocha")); queue.push(String::from("Espresso"));
println!("Orders waiting: {}", queue.len()); println!("First up: {}", queue[0]); println!("All: {queue:?}");}Orders waiting: 3First up: LatteAll: ["Latte", "Mocha", "Espresso"]Step by step:
Vec::new()creates an empty vector. The typeVec<String>means “a vector of Strings”.- The vector must be
mutbecause we add to it. .push(...)adds a value to the end..len()gives the number of items.queue[0]reads by index, the position number. Counting starts at 0.
There’s also a shortcut macro, vec!, for creating a vector with starting values:
let prices_cents = vec![450, 300, 325];Safe reading with get
What if you ask for position 10 in a list of 3?
Warning
queue[10] on a 3-item vector panics (crashes) with “index out of bounds”. When the position might not exist, use .get(10) instead. It returns an Option: Some(&item) or None, which you already know how to handle from Option and Result.
match queue.get(10) { Some(order) => println!("Order 11: {order}"), None => println!("There's no order 11"),}Removing items
fn main() { let mut queue = vec![String::from("Latte"), String::from("Mocha")];
let served = queue.remove(0); println!("Served: {served}");
if let Some(last) = queue.pop() { println!("Also served: {last}"); } println!("Queue empty? {}", queue.is_empty());}Served: LatteAlso served: MochaQueue empty? true.remove(0)takes out the item at index 0 and gives you ownership of it. Everything behind it shifts forward..pop()takes the last item. It returnsOptionbecause the vector might be empty..is_empty()is a friendly way to checklen() == 0.
Looping with for
The for loop is how you visit every item. How you write it decides ownership, and this is important:
fn main() { let mut prices_cents = vec![450, 300, 325];
// 1. Borrow read-only: look at each item for price in &prices_cents { println!("Price: {price}"); }
// 2. Borrow mutably: change each item for price in &mut prices_cents { *price += 25; // everything up by 25 cents }
// 3. Take ownership: the vector is used up let mut total = 0; for price in prices_cents { total += price; } println!("Total after increase: {total} cents");}Price: 450Price: 300Price: 325Total after increase: 1150 cents| Loop | Each item is | Vector afterwards |
|---|---|---|
for x in &v |
&T (read-only borrow) |
still usable |
for x in &mut v |
&mut T (mutable borrow) |
still usable, maybe changed |
for x in v |
T (owned) |
moved, can’t be used |
Tip
When in doubt, loop with &v. It’s the most common choice and leaves your vector untouched.
Notice the *price += 25 from the Borrowing lesson: * follows the reference so we can change the number it points to.
HashMap: look things up by key
A vector finds things by position. But to find the price of a “Mocha”, you don’t want to remember that it’s item number 1. You want to look it up by name. That’s a HashMap<K, V>: a collection of key → value pairs.
Analogy: the menu board. You look up the drink (the key) and read off its price (the value).
HashMap isn’t loaded automatically, so you bring it in with a use line at the top of the file:
use std::collections::HashMap;
fn main() { let mut menu: HashMap<String, u32> = HashMap::new();
menu.insert(String::from("Latte"), 450); menu.insert(String::from("Mocha"), 475); menu.insert(String::from("Espresso"), 300);
match menu.get("Mocha") { Some(cents) => println!("Mocha: {cents} cents"), None => println!("Not on the menu"), }
menu.insert(String::from("Latte"), 460); // price rise println!("Latte is now {} cents", menu["Latte"]); println!("Items on menu: {}", menu.len());}Mocha: 475 centsLatte is now 460 centsItems on menu: 3use std::collections::HashMap;makes the type available.stdis Rust’s standard library.HashMap<String, u32>means “keys are Strings, values are u32 prices”..insert(key, value)adds a pair. Inserting an existing key replaces its value..get("Mocha")returnsOption<&u32>, because the key might not exist.menu["Latte"]also works, but it panics if the key is missing, just like indexing aVec.
Looping over a HashMap
for (name, cents) in &menu { println!("{name}: {cents}");}Each loop gives you a (key, value) pair. The order is not guaranteed and may change between runs.
Note
A HashMap doesn’t keep things in the order you added them. If you need a sorted order, there’s BTreeMap in the same std::collections module, which keeps keys sorted.
Counting with entry
A classic pattern is counting things, like how many of each drink were sold today:
use std::collections::HashMap;
fn main() { let sales = vec!["Latte", "Mocha", "Latte", "Espresso", "Latte"]; let mut counts: HashMap<&str, u32> = HashMap::new();
for drink in sales { let count = counts.entry(drink).or_insert(0); *count += 1; }
println!("Lattes sold: {}", counts["Latte"]);}Lattes sold: 3for drink in salestakes each&strout of the vector. We don’t needsalesafterwards, so it’s fine to use it up..entry(drink)finds the spot for that key..or_insert(0)puts in0if the key wasn’t there yet, and gives back a&mut u32to the count.*count += 1adds one to it.
String vs &str
Rust has two main text types, and every beginner wonders why.
Stringis owned, growable text stored on the heap. You can add to it. It’s like your own notepad.&str(a string slice) is a borrowed view of some text that lives somewhere else. You can read it but not grow it. It’s like reading the menu board.
Text written in quotes, like "Latte", is a &str baked right into your program.
fn main() { let mut note = String::from("Oat latte"); note.push_str(", extra hot"); note.push('!');
let first_word: &str = ¬e[0..3]; let customer = "Mia"; let label = format!("{customer}: {note}");
println!("{label}"); println!("Starts with: {first_word}");}Mia: Oat latte, extra hot!Starts with: OatString::from(...)makes an ownedString..to_string()does the same thing..push_stradds text, and.pushadds a singlechar.¬e[0..3]borrows a slice: bytes 0 up to (not including) 3. That’s"Oat".format!builds a newStringfrom pieces, likeprintln!but without printing.
Which one should you use?
- In struct fields and when you need to own or change text:
String. - For function parameters that only read text:
&str. It accepts both&Stringand"literals".
Warning
Slicing text by byte position, like ¬e[0..3], panics if the position lands in the middle of a multi-byte character such as é or an emoji. For everyday beginner code, use methods like .split_whitespace(), .contains() or .starts_with() instead of slicing by numbers.
Try it yourself
- Create a
Vec<u32>of three order totals in cents:1250,480,900. Use aforloop over&totalsto add them up, then print the sum and the number of orders.
Show solution
fn main() { let totals: Vec<u32> = vec![1250, 480, 900]; let mut sum = 0;
for total in &totals { sum += total; }
println!("{} orders, {} cents in total", totals.len(), sum);}3 orders, 2630 cents in total- Build a
HashMap<&str, u32>for the café’s stock:"Croissant" → 12,"Muffin" → 0. Loop over it and print"<item>: SOLD OUT"when the count is 0, otherwise"<item>: <count> left".
Show solution
use std::collections::HashMap;
fn main() { let mut stock: HashMap<&str, u32> = HashMap::new(); stock.insert("Croissant", 12); stock.insert("Muffin", 0);
for (item, count) in &stock { if *count == 0 { println!("{item}: SOLD OUT"); } else { println!("{item}: {count} left"); } }}The lines may print in either order, because HashMap doesn’t keep insertion order.
Recap
Vec<T>is a growable, ordered list. Usepush,pop,remove,len, and.get(i)for safe reading.HashMap<K, V>stores key → value pairs for fast lookup by key..getreturns anOption.for x in &vborrows,for x in &mut vlets you change items, andfor x in vconsumes the collection.Stringis owned, growable text.&stris a borrowed view of text. Take&strin function parameters.
What’s next
So far, errors have been handled one match at a time. In Error Handling with ? you’ll learn a much shorter way to pass errors along.
0 of 35 lessons complete