Rust Program to Iterate over a HashMap


Iterate over a HashMap

Rust Programming Language


Iterate over a HashMap


Problem


Rust program that iterates over a HashMap.

Input


use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    
    map.insert("apple", 3);
    map.insert("banana", 2);
    map.insert("orange", 5);
    
    println!("Map: {:?}", map);
    
    for (key, value) in &map {
        println!("{}: {}", key, value);
    }
}{codeBox}

Output


Map: {"apple": 3, "banana": 2, "orange": 5}
apple: 3
banana: 2
orange: 5{codeBox}

Explanation


In this example, we create a new HashMap and insert some key-value pairs.

We then print the contents of the map using println!("Map: {:?}", map);.

Finally, we iterate over the map using a for loop and print each key-value pair using println!("{}: {}", key, value);. The for loop iterates over references to the key-value pairs in the map, and the (key, value) pattern destructures each pair into its key and value components.

This shows the contents of the map, followed by each key-value pair printed on a separate line in the order they were added to the map. Note that the order of iteration is not guaranteed for HashMaps.

Post a Comment