Rust HashMap ExamplesStore keys with associated values using the HashMap collection. Call the insert and get functions.
dot net perls

HashMap. Think of a key associated with a value: a tree is green, for example. We could loop over vectors to keep track of this link, but a HashMap is often faster.

Collection details. Part of std, we gain access to HashMap in Rust with a "use" directive. We can insert get values, and loop over the entire collection.

New HashMap. To begin, we create a HashMap and specify the key and value types. The type of "animals" could be omitted, and the compiler would resolve it for us.

Step 1 We create an animals HashMap with str keys and integer values. We add 2 keys with 1 associated value each to the map.

Step 2 We print the value of the HashMap at the key "bird" which resolves to the value 100 (this was added in the first insert call).

Rust program that creates HashMap
use std::collections::HashMap; fn main() { // Step 1: create HashMap and insert data. let mut animals: HashMap<&str, u32> = HashMap::new(); animals.insert("bird", 100); animals.insert("cat", 200); // Step 2: get value from HashMap. println!("{}", animals.get("bird").unwrap()); }

For-loop. Critical to using a HashMap in many programs is looping over the collection. For the clearest code, we call iter() and loop over the key and values in one loop.

Part 1 We create a new HashMap and then add 2 keys and 2 values. The compiler figures out the HashMap has string keys and values.

Part 2 We use the for-in loop syntax, and iterate over HashMap by calling iter(). We print all the keys, and each key's associated value.

Rust program that loops over HashMap
use std::collections::HashMap; fn main() { // Part 1: create new HashMap. let mut items = HashMap::new(); items.insert("tree", "green"); items.insert("hat", "yellow"); // Part 2: call iter to loop over the keys and values. for (key, value) in items.iter() { println!("ITER KEY, VALUE: {} {}", key, value); } }
ITER KEY, VALUE: hat yellow ITER KEY, VALUE: tree green

Match get example. Sometimes a key is not found in a HashMap. In this case, get() will return None—we can use a match expression to handle a key that is not found.


Here The HashMap contains the keys "green" and "red," but we try to access "orange." The "None" case in match is selected.

Rust program that uses match with HashMap
use std::collections::HashMap; fn main() { let mut colors = HashMap::new(); colors.insert("green", 1); colors.insert("red", 5); // Use match to handle keys that are not found. match colors.get("orange") { Some(value) => println!("VALUE: {}", value), None => println!("NOT FOUND") } }

Contains_key. Sometimes we want to see if a key exists in the HashMap, and we don't need the value. We can use contains_key for this purpose—it returns a boolean.

Rust program that uses contains_key
use std::collections::HashMap; fn main() { let mut zoo = HashMap::new(); zoo.insert("bird", 10); // See if bird is found in the zoo HashMap. if zoo.contains_key("bird") { println!("CONTAINS BIRD") } }

Len. We can access the count of keys in a HashMap with the len and is_empty functions. When zero entries are present, is_empty() returns true.

Tip Each entry (a key-value pair) counts as 1—so len() returns the number of keys in the HashMap.

Rust program that uses len, is_empty
use std::collections::HashMap; fn main() { let mut ids: HashMap<u32, u32> = HashMap::new(); // A HashMap starts out empty. if ids.is_empty() { println!("EMPTY"); } // Add 2 entries. ids.insert(1, 10); ids.insert(2, 20); // Print count of keys. println!("LEN: {}", ids.len()); }

Mut error. When we insert() a key into a HashMap, we mutate the HashMap. If the HashMap was not declared as mutable (with "mut") this will cause an error.

So We should usually declare HashMap variables as mut. If we do not we will get a compile-time error.

Mut error:
| 7 | let items = HashMap::new(); | ----- help: consider changing this to be mutable: mut items 8 | items.insert("tree", "green"); | ^^^^^ cannot borrow as mutable error[E0596]: cannot borrow items as mutable, as it is not declared as mutable --> src\main.rs:9:5

Sort HashMap. We cannot directly sort a HashMap, but we can sort the keys and values themselves. And then we can loop over those sorted values.

Sort HashMap

Convert HashMap. Suppose we have a HashMap, and we want to have a Vector—we can perform a conversion to get a vector. And the opposite can be done as well.

Convert HashMap, vec

A summary. HashMap supports efficient, hashed lookup from key to value. Rust provides complete support for this kind of collection—we specify key and value types.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.