Start learning free

LESSON 239 OF 348 · HASH TABLE

Hash Maps in Rust in Rust

Lesson

Hash Tables, better known as Hash Maps, are just collections of key-value pairs. In other words, they are pieces of data (values) mapped to unique identifiers called properties (keys).

Hash Maps were designed to give us a way of, given a key, associating a value with it for very quick lookups.

In Rust, the Hash Map is implemented as a HashMap from the Standard Library.


Creation:

You create an empty Hash Map by declaring a HashMap<keyType, valueType>, where the keyType and valueType are the data types of the keys and values.

Let's declare a Hash Map that maps text values represing digits to their numerical value (e.g. "two" => 2). We wil map strings to integers, so the two types are &str and i32. We will name the map digit_value

use std::collections::HashMap;
let mut digit_value: HashMap<&str, i32> = HashMap::new();

Creating an empty dictionary takes O(1) time.


Initialization:

You can also add some key-value pairs in your dictionary at creation:

let mut digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

Accessing values:

A value is retrieved from a map by specifying its corresponding key in square brackets ([]):

let mut digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

// Accessing values:
println!("{}", digit_value["zero"]); // prints 0
println!("{}", digit_value["one"]); // prints 1

println!("{:?}", digit_value.get("three")); // prints None

As you can see, if you refer to a key that is not in the map, Rust returns None when using .get(). Accessing a missing key with [] will panic at runtime.

Accessing a value from a map takes O(1) time.


Adding an entry:

Adding an entry to an existing map is simply a matter of assigning a new key and value, via the insert() method:

let mut digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

// Adding new entries:
digit_value.insert("three", 3);

//The new Hash Map:
// {
//	"zero": 0,
//  "one":  1,
//	"three": 3
//}

Adding a new entry to a map takes O(1) time.


Updating an entry:

If you want to update an entry, you can just assign a new value to an existing key:

let mut digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

// Updating entries:
digit_value.insert("zero", 5);

//The new Hash Map:
// {
//	"zero": 5,
//  "one":  1
//}

Updating an entry from a map takes O(1) time.


Deleting entries:

The remove() method allows you to remove a key from a map:

let mut digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

// Removing an entry
digit_value.remove("zero");

//The new Hash Map:
// {
//  "one":  1
//}

If you try to delete a key that is not in the map, it won't do anything.

Deleting an entry from a map takes O(1) time.


Checking if a key exists:

You can check if a key exists in a map using the contains_key() method:

let digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

println!("{}", digit_value.contains_key("zero")); // prints true since the key exists

println!("{}", digit_value.contains_key("three")); // prints false since the key does not exist in the map

Checking if a key exists in the map is O(1) time.


Iterating over the map keys:

If we want to iterate over keys of the map, we can use the for loop along with the keys() method:

let digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

for key in digit_value.keys() {
    println!("{} is {}", key, digit_value[key]);
}

// This will print:
// one is 1
// zero is 0

Notice the order is not the same as initiated. HashMap keeps the data in random order

Iterating over a dictionary takes O(n) time.


Iterating using both the key and the value for simplicity:

If we want to iterate over both keys and values of the map, we can use the for loop along with the & operator as follows:

let digit_value = HashMap::from([
    ("zero", 0),
    ("one", 1),
]);

for (key, val) in &digit_value {
    println!("{} is {}", key, val);
}

// This will print:
// one is 1
// zero is 0

Notice the order is not the same as initiated. HashMap keeps the data in random order

Iterating over a HashMap takes O(n) time.


Assignment
Follow the Coding Tutorial and let's practice with HashMaps.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    Hash Map in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free