Iterate over a Rust HashMap using a for loop with the iter() method to access key-value pairs.
Use a for loop with the iter() method to iterate over key-value pairs in a HashMap.
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
for (key, value) in &scores {
println!("{key}: {value}");
}
}
Iterating over a HashMap is like going through a list of name tags and their corresponding scores one by one. You use a loop to grab each pair, allowing you to read or process the data stored inside without changing the map itself. This is the standard way to check every item in your collection.