w3resource

Rust HashMap Iteration: Printing Key-Value pairs

Rust Arrays: Exercise-2 with Solution

Write a Rust program that iterate over a HashMap and print each key-value pair.

Sample Solution:

Rust Code:

use std::collections::HashMap; // Import the HashMap type from the standard library

fn main() {
    // Create a HashMap to store key-value pairs
    let mut my_map: HashMap<&str, i32> = HashMap::new(); // Key: &str (string slice), Value: i32

    // Insert some key-value pairs into the HashMap
    my_map.insert("a", 1);
    my_map.insert("b", 2);
    my_map.insert("c", 3);

    // Iterate over the HashMap and print each key-value pair
    for (key, value) in &my_map {
        println!("Key: {}, Value: {}", key, value);
    }
}

Output:

Key: c, Value: 3
Key: b, Value: 2
Key: a, Value: 1

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::collections::HashMap;: This line imports the "HashMap" type from the standard library, allowing us to use HashMaps in our code.
  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let mut my_map: HashMap<&str, i32> = HashMap::new();: This line creates an empty HashMap named 'my_map' with keys of type '&str' (string slice) and values of type i32.
  • my_map.insert("a", 1);: This line inserts a key-value pair into the 'my_map' HashMap, where the key is the string slice "a" and the value is the integer 1. Similar lines insert additional key-value pairs.
  • for (key, value) in &my_map { ... }: This line starts a loop to iterate over each key-value pair in the my_map HashMap. The loop iterates using a reference to the HashMap (&my_map), and each iteration unpacks the key and value into variables 'key' and 'value'.
  • println!("Key: {}, Value: {}", key, value);: This line prints each key-value pair to the console. The key and value are interpolated into the string using {} placeholders.

Rust Code Editor:

Previous: Rust HashMap: Inserting Name-Age pairs.
Next: Rust HashMap Key existence Check & Message printing.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/collections_and_data_structures/rust-hashmaps-exercise-2.php