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.
1 2 3 4 5 | let mut my_map:HashMap<i32, String> = HashMap::new(); my_map.insert(1, "one".to_string()); my_map.insert(2, "two".to_string()); my_map.insert(3, "three".to_string()); |
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.
1 2 3 | for (k, v) in my_map.iter() { println!("key={}, value={}", k, v); } |
When we run the code snippet, we get the following output.
1 2 3 | key: 1 | value: one key: 3 | value: three key: 2 | value: two |
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.
1 2 3 4 5 6 7 8 | for (k, v) in my_map.iter_mut() { let v = "$".to_string(); println!("key={}, value={}", k, v); } for (k, v) in my_map.iter() { println!("key={}, value={}", k, v); } |
These codes will generate the following result.
1 2 3 4 5 6 | key=2, value=$ key=1, value=$ key=3, value=$ key=2, value=two key=1, value=one key=3, value=three |
On the other hand, with the into_iter(), we can use it in a for-in Rust loop.
1 2 3 4 | let iter = my_map.into_iter(); for t in iter { println!("{} {}", t.0, t.1) } |
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.
1 2 3 4 | for x in my_map.keys() { println!("{}", x); println!("{}", my_map.get(x).unwrap()); } |
When we run these codes, we get the following.
1 2 3 4 5 6 | 1 one 3 three 2 two |
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.
1 2 3 | for d in my_map.values() { println!("{}", d) } |
We tested the codes using Rust 1.53.0, and this post is now part of the Rust Programming Language For Beginners Tutorial.