In Rust, we can extract the keys and values from a HashMap using the iter() and keys() / get() / unwrap() functions.
Test Data
1 2 3 4 5 |
let 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()); |
Using iter()
Note that iter() return all key-value pairs in arbitrary order.
1 2 3 |
for (k, v) in my_map.iter() { println!("key={}, value={}", k, v); } |
Output 1
1 2 3 |
key: 1 | value: one key: 3 | value: three key: 2 | value: two |
Output 2
1 2 3 |
key: 2 | value: two key: 1 | value: one key: 3 | value: three |
Using keys()
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()); } |
Output 1
1 2 3 4 5 6 |
1 one 3 three 2 two |
Output 2
1 2 3 4 5 6 |
3 three 1 one 2 two |