Home

Search

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()); }
100

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

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()); }
EMPTY LEN: 2

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

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

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