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 break down how HashMaps work and how to use them in our Rust programs.
HashMap module
To use a HashMap, we need to imp0rt the HashMap module from the Rust standard collections library.
An import statement is as shown:
Once imported, we can use it to work with HashMaps in Rust.
Rust Create HashMap
We can define a new empty hash map using the new method. An example is as shown below:
fnmain() {
letmutuser_info = HashMap::new();
}
The above creates a new empty hash map that stores user information. To add elements to the hash map, we can use the insert method as shown in the example below:
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 hash map, we can use the println! method with the debug trait as shown:
This should return the complete hash map information.
Rust Iterate Hash Map.
We can iterate over a hash map using the iter method. An example illustration is as shown below:
println!("{}: {}", key, value);
}
The iter method will return a set of keys and their corresponding values. An example output is as shown:
Russell : California
Mason: Virgina
Franklin: Colorado
Elise: Pennysylania
Rust Check If Key Exists
To check if a key exists within a hash map, you can use the contains_key() method. An example is as shown:
The function takes the key to lookup as an argument and returns a Boolean true if the key exists in the hash map.
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 as shown:
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 hash map by passing a unique value to an existing key. An example is as shown:
println!("{:?}", user_info.get("Mason"));
Since the key “Mason” already exists in the hash map, Rust automatically substitutes its value with the new one.
Rust Remove Key-Value
We can remove a key-value pair from a hash map using the remove method. The method takes the key we wish to remove as the argument.
An example is as shown:
Final Thoughts
HashMaps play a critical role in providing diversity and extensibility for your programs. Keep practicing!