Rust, Software Development

Rust – How to get Keys and Values from HashMap

In Rust, we can store key and value pairs using HashMap. This post shows how to store and extract the keys and values from a HashMap using the functions iter(), keys(), values(), get(), and unwrap().

Store Test Data Into a HashMap

Before we extract keys and values from a HashMap, let’s store some test data. Consider the following codes, which create a HashMap and store String literals using i32 values as HashMap keys.

For example, the codes store “one” with key 1, and “two” with key 2, and so on. Then, we can extract the keys and values from our HashMap instance using some Rust functions.

Loop Through Key And Value Pairs Using iter()

The HashMap instance implements the iter() function, which, however, returns all the key-value pairs in arbitrary order. Consider the following code snippet.

When we run the code snippet, we get the following output.

Alternatively, we could use the Rust functions iter_mut()  or into_iter(). Needless to state, we use the iter_mut() function when we want to modify the local variables for the keys and values during an iteration.  However, modifying these local variables does not modify the content of the HashMap content.

These codes will generate the following result.

On the other hand, with the into_iter(), we can use it in a for-in Rust loop.

Note that there are technical differences when using these Rust functions. Please see the documentation.

Use keys() to Extract only keys

Sometimes we want to extract only the keys instead of key-value pairs. We can do this using the keys()  function. Consider the following codes. Note that keys() also return keys in arbitrary order.

When we run these codes, we get the following.

On the other hand, we may want to retrieve only the values instead of just the keys. We could use the values() function as shown below.

We tested the codes using Rust 1.53.0, and this post is now part of the Rust Programming Language For Beginners Tutorial.

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