A HashMap contains a key and its corresponding value. In Rust, a hashing function determines how the key and value pairs are allocated in the memory managed.
Let us breakdown how HashMaps work and how to use them in our Rust programs.
HashMap Module
To use a HashMap, we need to import the HashMap module from the Rust standard collections library.
An import statement is provided below:
Once imported, we can use it to work with HashMaps in Rust.
Rust Create HashMap
We can define a new empty HashMap using the new method. An example is provided below:
fn main() {
let mut user_info = HashMap::new();
}
The previous example creates a new empty HashMap that stores user information. To add elements to the HashMap, we can use the insert method as shown in the example below:
fn main() {
let mut user_info = HashMap::new();
user_info.insert("Russell ", "California");
user_info.insert("Donna", "Wyoming");
user_info.insert("Franklin", "Colorado");
user_info.insert("Elise", "Pennysylania");
user_info.insert("Mason", "Virgina");
}
To print the HashMap, we can use the println! method with the debug trait as shown below:
This should return the complete hash map information as shown below:
Rust Iterate HashMap
We can iterate over a HashMap using the iter method. An example illustration shown below:
println!("{}: {}", key, value);
}
The iter method will return a set of keys and their corresponding values. An example output is provided below:
Russell: California
Mason: Virgina
Franklin: Colorado
Elise: Pennysylania
Rust Check If Key Exists
To check if a key exists within a HashMap, you can use the contains_key() method. An example is shown below:
The function takes the key to lookup as an argument and returns a Boolean true if the key exists in the HashMap.
Rust Retrieve Values
You can retrieve the values from a map using the get method. The function takes the key you wish to access as the argument and returns the corresponding value.
An example is provided below:
If the specified key exists in the collection, Rust will return the associated value and a None if the key is not found.
Rust Update HashMap
You can update a key-value pair in a HashMap by passing a unique value to an existing key. An example is provided below:
println!("{:?}", user_info.get("Mason"));
Since the key “Mason” already exists in the HashMap, Rust automatically substitutes its value with the new one:
Rust Remove Key-Value
We can remove a key-value pair from a HashMap using the remove method. The method takes the key we wish to remove as the argument.
An example is provided below:
Conclusion
HashMaps play a critical role in providing diversity and extensibility for your programs. This article provides a guide on using HashMaps in the Rust programming language and its different uses. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.