The HashMap in Rust, A Practical Example

Authors

A hash map, also known as a dictionary or associative array, is a collection of key-value pairs that allows for fast insertion and lookup.

In Rust, the standard library provides a hash map implementation through the HashMap type, which is part of the std::collections module.

Creating a HashMap In Rust

To create a HashMap, you'll need to specify the types for the keys and values it will store.

Here's an example of creating a HashMap that maps String keys to i32 values:

use std::collections::HashMap;

let mut scores = HashMap::new();

You can also create a HashMap using the collect method on a vector of tuples, where each tuple consists of a key and a value.

For example:

use std::collections::HashMap;

let teams = vec![("Red", 10), ("Blue", 3)];
let scores: HashMap<_, _> = teams.into_iter().collect();

Inserting and Retrieving Values

To insert a key-value pair into a HashMap, you can use the insert method.

If the key doesn't already exist in the map, the key-value pair is inserted and None is returned.

If the key does exist, the value is updated and the old value is returned.

use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert("Blue", 10);
scores.insert("Red", 25);

let score = scores.get("Blue");
println!("{:?}", score); // Some(10)

You can also use the get_mut method to retrieve a mutable reference to a value in the HashMap, or the entry method to insert a value if it doesn't exist and retrieve a mutable reference if it does.

Iterating Over a HashMap In Rust

To iterate over the key-value pairs in a HashMap, you can use a for loop:

use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Red", 25);

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

You can also use the keys and values methods to get an iterator over the keys or values in the HashMap respectively.

Here's an example program that demonstrates how to use a HashMap in Rust:

use std::collections::HashMap;

fn main() {
    // Create a new hash map
    let mut scores = HashMap::new();

    // Insert some key-value pairs
    scores.insert("Blue", 10);
    scores.insert("Red", 25);

    // Get the value for a key
    let score = scores.get("Blue");
    println!("{:?}", score); // Some(10)

    // Iterate over the key-value pairs in the map
    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }

    // Update the value for a key
    scores.insert("Blue", 50);
    println!("{:?}", scores.get("Blue")); // Some(50)

    // Get the value for a key if it exists, or insert a default value
    scores.entry("Green").or_insert(0);
    println!("{:?}", scores.get("Green")); // Some(0)
}

This program creates a HashMap called scores and inserts two key-value pairs: "Blue" -> 10 and "Red" -> 25.

It then retrieves the value for the key "Blue" and prints it to the console.

Next, it iterates over the key-value pairs in the map and prints them.

Then, it updates the value for the key "Blue" to 50 and retrieves it again.

Finally, it uses the entry method to insert a default value of 0 for the key "Green" if it doesn't already exist in the map, and then retrieves the value for that key.

Conclusion

The HashMap type in Rust is a useful data structure for storing and quickly accessing key-value pairs.

It's efficient, flexible, and easy to use.

Whether you need a simple lookup table or a more complex data structure, a HashMap is a great choice.

TrackingJoy