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!
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.
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.
HashMaps provide methods to modify values and remove elements by their keys. To remove an element, use .remove by passing in a variable reference. To modify the value stored in a key, you can reinsert the key with its new value or use .get_mut. .get_mut accepts a reference to the key.
- The
removemethod deletes the key-value pair from the HashMap. - Re-inserting the key "one" with the value 1, overrides the original value of the key.
- The
get_mutmethod obtains a mutable reference to the value associated with the key, which allows us to modify it.
Checking for the existence of keys in a HashMap can be easily done using the contains_key method. The value passed to contains_key must be a reference.
- The
contains_keymethod checks whether a specified key exists in theHashMap.
As with other data structures in Rust, managing ownership and borrowing is crucial when working with HashMaps. Elements added to a HashMap must adhere to Rust's ownership rules.
- We create a
Stringcalleds. - We create a
HashMapmap, and insertswith a key and anotherStringelement with a different key. - Adding
sto theHashMaptransfers ownership of "Hello" fromstomap.
HashMaps can be passed to functions as references or by value. Understanding how to pass HashMaps to functions allows for more modular and reusable code. Similar to vectors and Hashsets, a HashMap is never copy type, even if the data held in the HashMap is copy type.
display_hashmap_referencetakes a reference to aHashMap, so it doesn't take ownership, allowing theHashMapto remain available after the function call.display_hashmap_copytakes aHashMapby value. Even though the elements are a copyable data type (i32), aHashMapis not copy type, thus ownership is transferred.
Great job! You've learned about creating and managing HashMaps in Rust, including adding, accessing, modifying, and removing elements. You've also explored how to check for the presence of keys, understood ownership in HashMaps, and learned how to pass HashMaps to functions effectively.
HashMaps are an indispensable tool for organizing and managing key-value pairs. Applying these concepts will significantly enhance your ability to write efficient and robust Rust programs.
Now that you have a solid understanding of HashMaps, it's time to try some hands-on practice to reinforce your learning. Dive into the exercises ahead and start experimenting with HashMaps. Happy coding!
