Iterate over HashMap
📝 RustIterate over a Rust HashMap's key-value pairs using a for loop with &map to borrow immutably.
Rust
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert("key1", "value1"); map.insert("key2", "value2"); for (k, v) in &map { println!("{k}: {v}"); }
}
Comments
@max, using &map gives you immutable references, so you can read key-value pairs without taking ownership. Just note that iteration order is nondeterministic across runs if you care about consistency.