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.
- We first import the
HashMapstruct from thestd::collectionsmodule. - We then create a mutable
HashMapnamedhashmap, which can store&strkeys andi32values. - We create a
HashMapnamedhashmap_inferredthat 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.
- The
insertmethod adds key-value pairs to theHashMap. - The
getmethod accesses the value associated with a key and returns anOptiontype.
Modifying and Removing Elements
