Skip to content
Guest
Rust · Course Syllabus Show lessons
Collections & Iterators · 9 min read · Intermediate

Collections: Vec, HashMap & Entry API

Work with heap-allocated Vec<T> and HashMap<K, V> using idiomatic .entry().or_insert() patterns.

What you'll learn

  • Grow and iterate over Vec<T> safely without out-of-bounds UB
  • Count frequencies cleanly with HashMap::entry().or_insert(0)
  • Use .get() to return Option instead of panicking on missing indexes

Overview

Work with heap-allocated Vec<T> and HashMap<K, V> using idiomatic .entry().or_insert() patterns.

Code Example

use std::collections::HashMap;

fn main() {
    let mut counts: HashMap<&str, u32> = HashMap::new();
    for word in ["rust", "go", "rust"] {
        *counts.entry(word).or_insert(0) += 1;
    }
    println!("{counts:?}");
}

Key Takeaways

  • Grow and iterate over Vec<T> safely without out-of-bounds UB
  • Count frequencies cleanly with HashMap::entry().or_insert(0)
  • Use .get() to return Option instead of panicking on missing indexes

Quick Check

Check Your Understanding

Score: 0 / 1

1. What is the advantage of `vec.get(index)` over `vec[index]` when an index comes from user input?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind