HashMaps in Rust

Introduction to HashMaps in Rust

Hello! Today, we will focus on another powerful and versatile data structure in Rust's std::collections module — HashMaps. HashMaps are invaluable when you need to establish a mapping between a set of keys and a corresponding set of values.

HashMaps store key-value pairs, making it easy to quickly look up values based on their associated keys. This concept is similar to dictionaries in other programming languages like Python. Let's dive in and get familiar with HashMaps!

Creating a HashMap

In Rust, creating a HashMap involves using the HashMap struct from the std::collections module. When creating a new Hashmap, add the data type of the keys and data type of the values inside <>. You can also create an empty HashMap without specifying types, and Rust will infer the types based on how you insert an element into the HashMap for the first time.

use std::collections::HashMap;

fn main() {
    // Create a new HashMap with explicit types
    let mut hashmap: HashMap<&str, i32> = HashMap::new();

    // Create a new HashMap with inferred types
    let mut hashmap_inferred = HashMap::new();
}
  • We first import the HashMap struct from the std::collections module.
  • We then create a mutable HashMap named hashmap, which can store &str keys and i32 values.
  • We create a HashMap named hashmap_inferred that will infer the data types when an element is added.

Adding and Accessing Elements

Once you have a HashMap, you can add elements using the insert method. To access a value from a Hashmap use .get followed by the key name. The .get method only accepts a reference.

use std::collections::HashMap;

fn main() {
    let mut hashmap: HashMap<&str, i32> = HashMap::new();

    // Add elements
    hashmap.insert("one", 1);
    hashmap.insert("two", 2);
    hashmap.insert("three", 3);

    // Access a value
    let value = hashmap.get("two");
    println!("Value under 'two': {:?}", value); // Prints: Value under 'two': Some(2)

    println!("{:?}", hashmap); // Prints: {"one": 1, "two": 2, "three": 3}
}
  • The insert method adds key-value pairs to the HashMap.
  • The get method accesses the value associated with a key and returns an Option type.

Modifying and Removing Elements

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal