Iterate over a HashMap in Rust

Iterate over each key-value pair in a hash map using a for loop.

// use `HashMap` from `collections` module of the standard library
use std::collections::HashMap;

// create an empty hash map
let mut ipl_season_2022 = HashMap::new();

// add elements to the hash map
ipl_season_2022.insert(String::from("SRH"), 12);
ipl_season_2022.insert(String::from("RCB"), 16);
ipl_season_2022.insert(String::from("LSG"), 18);
ipl_season_2022.insert(String::from("RR"), 18);

// use may also use to_string()
ipl_season_2022.insert("GT".to_string(), 20);

for (key, value) in &ipl_season_2022 {
	println!("{} : {}", key, value);
}

GT : 20
LSG : 18
RCB : 16
RR : 18
SRH : 12

Use a hash map when

  • You want to associate arbitrary keys with an arbitrary value.
  • You want a cache.
  • You want a map, with no extra functionality.

Here is the HashMap API reference.

Read more on Storing keys with associated values in Hash maps, The Rust Programming Language.