13 / 35

Core Rust Concepts· 14 min read· Lesson 13 of 35

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.

src/main.rs
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:?}");
}
Output
Orders waiting: 3
First up: Latte
All: ["Latte", "Mocha", "Espresso"]

Step by step:

  1. Vec::new() creates an empty vector. The type Vec<String> means “a vector of Strings”.
  2. The vector must be mut because we add to it.
  3. .push(...) adds a value to the end.
  4. .len() gives the number of items.
  5. 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

src/main.rs
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());
}
Output
Served: Latte
Also served: Mocha
Queue empty? true
  1. .remove(0) takes out the item at index 0 and gives you ownership of it. Everything behind it shifts forward.
  2. .pop() takes the last item. It returns Option because the vector might be empty.
  3. .is_empty() is a friendly way to check len() == 0.

Looping with for

The for loop is how you visit every item. How you write it decides ownership, and this is important:

src/main.rs
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");
}
Output
Price: 450
Price: 300
Price: 325
Total 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:

src/main.rs
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());
}
Output
Mocha: 475 cents
Latte is now 460 cents
Items on menu: 3
  1. use std::collections::HashMap; makes the type available. std is Rust’s standard library.
  2. HashMap<String, u32> means “keys are Strings, values are u32 prices”.
  3. .insert(key, value) adds a pair. Inserting an existing key replaces its value.
  4. .get("Mocha") returns Option<&u32>, because the key might not exist.
  5. menu["Latte"] also works, but it panics if the key is missing, just like indexing a Vec.

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:

src/main.rs
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"]);
}
Output
Lattes sold: 3
  1. for drink in sales takes each &str out of the vector. We don’t need sales afterwards, so it’s fine to use it up.
  2. .entry(drink) finds the spot for that key.
  3. .or_insert(0) puts in 0 if the key wasn’t there yet, and gives back a &mut u32 to the count.
  4. *count += 1 adds one to it.

String vs &str

Rust has two main text types, and every beginner wonders why.

  • String is 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.

src/main.rs
fn main() {
let mut note = String::from("Oat latte");
note.push_str(", extra hot");
note.push('!');
let first_word: &str = &note[0..3];
let customer = "Mia";
let label = format!("{customer}: {note}");
println!("{label}");
println!("Starts with: {first_word}");
}
Output
Mia: Oat latte, extra hot!
Starts with: Oat
  1. String::from(...) makes an owned String. .to_string() does the same thing.
  2. .push_str adds text, and .push adds a single char.
  3. &note[0..3] borrows a slice: bytes 0 up to (not including) 3. That’s "Oat".
  4. format! builds a new String from pieces, like println! 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 &String and "literals".

Warning

Slicing text by byte position, like &note[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

  1. Create a Vec<u32> of three order totals in cents: 1250, 480, 900. Use a for loop over &totals to 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);
}
Output
3 orders, 2630 cents in total
  1. 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. Use push, pop, remove, len, and .get(i) for safe reading.
  • HashMap<K, V> stores key → value pairs for fast lookup by key. .get returns an Option.
  • for x in &v borrows, for x in &mut v lets you change items, and for x in v consumes the collection.
  • String is owned, growable text. &str is a borrowed view of text. Take &str in 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

Search lessons

Type to search all lessons.