In Rust, creating a hash map typically involves using the HashMap type from the standard library, located in the std::collections module. A hash map allows you to store key-value pairs where keys are unique.
Introducing HashMap
First, you need to import HashMap. You can do this by adding the following code at the top of your file:
rustuse std::collections::HashMap;
Creating an Empty HashMap
Creating a new empty hash map:
rustlet mut map = HashMap::new();
This line creates a mutable variable map of type HashMap, which is initially empty.
Adding Elements to HashMap
To add key-value pairs to a hash map, you can use the .insert() method:
rustmap.insert("key1", "value1"); map.insert("key2", "value2");
Here, we insert two key-value pairs into the hash map. Keys and values can be any types that implement Eq and Hash (for keys) and Clone (for values).
Accessing Elements in HashMap
To access values in a hash map, you can use the .get() method and pass the key you want to query:
rustif let Some(value) = map.get("key1") { println!("The value for 'key1' is {}", value); } else { println!("'key1' is not found in the map"); }
Example
Here is a complete example demonstrating how to create and use HashMap in Rust:
rustuse std::collections::HashMap; fn main() { // Creating a new HashMap let mut scores = HashMap::new(); // Adding elements scores.insert("Blue", 10); scores.insert("Yellow", 50); // Accessing elements let team_name = String::from("Blue"); if let Some(score) = scores.get(&team_name) { println!("{} team's score is {}", team_name, score); } else { println!("No score found for {}", team_name); } // Updating HashMap scores.insert("Blue", 25); // Iterating over HashMap for (key, value) in &scores { println!("{}: {}", key, value); } }
In this example, we create a hash map representing team scores and demonstrate how to add, access, and update data, as well as iterate over all elements in the hash map. These operations are very common in everyday programming, and understanding them is crucial for effectively using hash maps.