Rust Foundations·Ownership as a design tool

Collections and iterators

Vec and HashMap cover common storage; iterators express transformations lazily.

Intermediate 14 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Use Vec<T> for ordered sequences.
  • Use HashMap<K, V> for key lookup.
  • Borrow iterators when you do not need ownership.

In plain English

A Vec is a growable array; a HashMap maps keys to values. Iterator adapters such as map, filter and collect are lazy until consumed. Prefer iterators when they make the intent clearer than index loops.

iterators.rsRust
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("HTML", 8);
    scores.insert("CSS", 12);

    let total: i32 = scores.values().sum();
    let short: Vec<&str> = scores
        .iter()
        .filter(|(_, minutes)| **minutes < 10)
        .map(|(title, _)| *title)
        .collect();

    println!("{total} {short:?}");
}
Your turn

Sum lesson minutes

Medium

Given a Vec of (title, minutes), sum the minutes and collect titles under 15 minutes.

RUST · starter
let lessons = vec![("HTML", 8), ("CSS", 12), ("Grid", 16)];
Check your understanding before moving on.
Knowledge checkQuestion 1

Which method turns an iterator into a collection?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course