Rust, Software Development

Rust HashMap Examples

This post shows Rust HashMap basic examples, particularly for beginners. A map is a type of data structure that allows us to store key-value pair data. We may have learned it from other programming languages like Java. In Rust, the HashMap struct represents and implements the concept of a map.

Declare a Rust HashMap Example

Creating a map in Rust is easy using HashMap. Consider the following line of codes.

Like other Rust collections, HashMap allows us to use generics to define the key and value types. The Rust codes create a HashMap with String key-value pair data in our example. Then, we can use the following codes to put data into the map.

The Rust codes insert the course name as a key and the student name enrolled in that course. Meanwhile, if we want to store numeric course IDs instead of course names, we can do so as shown below.

Notice we adjusted the Rust HashMap declaration in our example and used the i32 type for the key but kept the String type for the student name. To retrieve a value from a Rust HashMap, we can use either one of the following functions.

Custom Key For Rust Map Using Struct

In some situations, we may want a custom key for our Rust Map instead of using i32, String, or other Rust’s default data types. We can do so by creating structs. Let’s suppose that now we identify any course by its ID and country code. Instead of just the ID alone, we throw in a country code and name the key as “course identity.”

Consider the following struct definition. Notice we use the #[derive] to implement those Rust traits – Eq, Hash, PartialEq.

Then, we need to modify our codes as follows.

Loop Through Rust Map

To loop through the Rust HashMap key-value pairs, we need the map’s iterator, and we can get that using either one of these functions – iter(), iter_mut(), and into_iter().

We can also retrieve just the keys instead of the key-value pairs.

Or just the values!

There you go! By the way, we tested the Rust HashMap example codes using Rust 1.59.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like