Iterators and HashMap fundamentals
Transform collections idiomatically and count frequencies.
- Use iterator adapters and
HashMapfor practical data work.
Iterators provide composable collection processing through adapters like map, filter, and collect. HashMap<K, V> stores key-value associations efficiently.
1use std::collections::HashMap;
2
3fn main() {
4 let words = ["rust", "safe", "rust"];
5 let mut counts: HashMap<&str, i32> = HashMap::new();
6
7 for word in words {
8 *counts.entry(word).or_insert(0) += 1;
9 }
10
11 println!("{}", counts["rust"]);
12}2
entry(...).or_insert(...) is the idiomatic way to update counters in a map. Iterator chains keep data transformations concise and expressive.
Try it
Up to 15 XPChoose the right collection pattern
Sort each task by the iterator/hash-map pattern that solves it best.
“Create a vector of doubled numbers from a list”
“Count how many times each word appears”
“Keep only even numbers from a vector”
“Track request count per endpoint path”
Key takeaways
Use iterator adapters and
HashMapfor practical data work.Rust uses types and ownership rules to prevent common bugs.
Small experiments build intuition quickly.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Rust
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.
Count character frequencies
Read one line and print the count of lowercase a characters.
- Multiple a letters
- No a
Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…