Very Simple Guide to Rust Hashmaps | July 2020

rust hashmaps, rust hashmaps tutorial

If you have been working with the Rust language, then you most likely have encountered so many new concepts. If you come from a high-level language background, then you probably have never thought about stacks and heaps, references, mutable and immutable, etc. The strict rules of Rust may have given you nightmares, and you probably are thinking about quitting Rust. The borrowing rule that comes with the Rusts’ strings would have been scary. There are just so many new things to learn.

One feature that is overlooked but is powerful and other languages implement this feature, it is known as hashmaps. Rust hashmaps, like many other programming languages, are a powerful and useful feature to know. You can use them as temporary storage, although there is a much more useful feature called Structs you would not want to create a struct and define methods on it just to do a simple task. Rust hashmaps come with excellent methods that you can use to perform a nice and simple task. We will use and list these methods in our rust hashmaps tutorial.

In this article, we will write a simple and straight forward rust hashmaps tutorial that will help you in understanding and working with rust hashmaps.

What is Rust Hashmaps

Before starting with the Rust hashmaps tutorial, we need to know what hashmaps are in general. Rust hashmaps are a part of types of data structures known as collections. Collections are data structures that store multiple values in a single time. An integer data type can store a single value, a boolean data type can store a single boolean value, but collections can store multiple integers, or booleans, or strings. Hashmaps are part of these Collections.

Hashmaps stores values with the help of keys. Keys can be of any data type, and values can be of any data type. With the help of a key, you can access a value. When you work with arrays, and you have to get a specific value, you would have to search the whole array if you do not know the index. When you associate a key with a value, it gets easier to remember the key. You can think of hashmaps as a phone directory. When you have to search for someone’s number, you can look up their name, and then the complicated phone number (that is hard to remember) also shows up.

Many other programming languages implement this kind of data structure, but they have different names for it. Hash, map, associative array, object, dictionary, etc. are the name of the same data structure. They all work just like Rust Hashmaps.

Now we will start with our rust hashmaps tutorial

Creating the Hashmap

It is important to note that out of the three common collections, hashmaps are the least used. This is the reason why they are not brought into scope in the prelude. In order to work with hashmaps, we would have to call them from the collections portion of the standard library. We would do it like this.

rust hashmaps, rust hashmaps tutorial

Alright, now hashmaps can be created and worked with. As I said earlier, we will keep things simple in this Rust hashmaps tutorial. As hashmaps are not used that much, that is why they do not have much support from the library. This is why there is no macro to create a hashmap. In order to create a hashmap, we will write this.

rust hashmaps, rust hashmaps tutorial

Hashmaps are stored on the heap and can dynamically allocate if the data gets too big. If you know the number of keys that will be held in the hashmap when it is created, you can specifically write the number of keys while creating the hashmap. Using this way, anytime you add data into the hashmap, it will not reallocate itself; hence it will not be a memory-intensive task. Whatever the number you give, it is guaranteed to hold that much data.

rust hashmaps, rust hashmaps tutorial

As we will try to make everything as clear as possible in this rust hashmaps tutorial, one thing that we can do to make sure that this hashmap has a capacity of 5, or more than 5, we can write this:

rust hashmaps, rust hashmaps tutorial

The value that will be printed on the screen will be 5 or greater than 5.

Inserting Data into the Hashmap

Once we have a hashmap created, we would have to add some data to it. We cannot just create a hashmap and not use it, that is just silly. Remember that the data inserted into the hashmap is in key-value pair. The keys that we assign in the hashmap has to have the same data type, and all the values should have the same data type too.

For, e.g., if you add the first key which has a data type of i32, then the rest of the keys that will be added should have a data type of i32. You either specifically write, what data types that you will add as keys and values, or the compiler infers the type by looking at the first key-value pair that was added.

When we want to add data to the hashmap, we use the insert(key, value) method. We will add grocery items in our hashmap. The item name will be given as the key, and the number of items that we have bought will be given as a value. In our Rust hashmaps tutorial, we have named our hashmap as hashmap, so:

rust hashmaps, rust hashmaps tutorial

In our rust hashmaps tutorial, we are storing String data type as keys, and i32 as values. Every single line will add new data to our hash map. The value of 10 will be associated with the “Egg” key, and the rest of the values will be stored in the same way.

Remember that the key in the hashmap has to be unique. If we insert a value with the key that is present in the hashmap, the previous value will get overwritten. This way of updating the values is known as overwriting and can be used if needed. There are other ways of updating the values that we will see later in our rust hashmaps tutorial.

Getting the Value out of the Hashmap

In this Rust hashmaps tutorial, we want to cover every sing basic functionality that hashmaps provide. When you assign a value to a variable, working with that value and getting that value is easy. When we have data inside arrays or tuples, we can get those values with the help of indexing.

How do you get the value out of the hashmap? There are two easy ways of doing this job. You can either enter the key name, just like how you index the array, instead of entering a number, you input the reference of the key name. Getting a value from the hashmap using this way is dangerous. If the key does not exist, then the program will panic during runtime and will crash. Remember that we entered the “Egg” key inside our hashmap, we will get the value out of it like this:

rust hashmaps, rust hashmaps tutorial

If you print the number_of_eggs variable, you will get a value of 10.

Remember, if you entered a wrong key that did not exist in the hashmap, the program would have crashed.

Another way of accessing the value out of the hashmap is by using the get(key) method. The get() method returns the Option enum. If the key exists in the hashmap, it will be returned in Some(), but if the key does not exist, None would return. You can then handle the program flow on your own without any crashes and errors. We will list the example of how you can access the value in hashmap, in out rust hashmaps tutorial.

rust hashmaps, rust hashmaps tutorial

If you entered the wrong key here, you would have gotten. None. There would have been no crashes and errors.

Updating the Hashmap

We have previously mentioned one way of updating the value in our rust hashmaps tutorial. You can use the insert method to overwrite the value associated with a key. There is one other way of updating a value in rust hashmaps. If you are not sure if the key exists or not, you can use the entry(key) method along with the or_insert(value) method. If the key does not exist, the value that you have given in the or_insert() method will be associated with the key. If the key already exists, then the new value will be dumped, and the previous value will persist. Here is an example of adding a key that does not exist in our hashmap.

rust hashmaps, rust hashmaps tutorial

As there was no key named “Cereal,” a new key will be added with the value 7 associated with it.

Removing Data out of the Hashmap

One last thing that is left in our rust hashmaps tutorial is learning about deleting the data out of the hashmap. When we enter the wrong data, it would be important to remove the key. If we cannot do that, hashmap will be filled with useless data that is taking up space. There is an easy method that we can use to remove a key and the value associated with it. In our example, we will remove the “Egg” key. If the key does not exist, None will be returned.

rust hashmaps, rust hashmaps tutorial

Now if you try to read the value associated with the “Egg” key, you will get None.

Simple Exercise

Alright, we have learned lots of basics of hashmaps in our rust hashmaps tutorial. You now know how to insert a key in a hashmap, read the value out of the key, how to update the key, and how to remove the key. One simple thing that now you can try is to make a simple user database. I will give you some hints

Make a program in which you can input a new user, and then read all of the users present in the database. You will use hashmaps to store data for an individual person. You will store all of these hashmaps in a vector. It is up to you how you want to display the inserted users. You can update and delete the users too.

The user should have id, name, age, and job key. Both the key and the value should have the String datatype.

You can look at the Rust hashmaps documentation to learn about more methods that you can use in your exercise.


If you liked this article, you could also look at it.

8 thoughts on “Very Simple Guide to Rust Hashmaps | July 2020”

  1. Hello! I could have sworn I’ve been to this web site before but after looking at a few of the articles I realized it’s new to me.
    Anyways, I’m certainly happy I found it and I’ll be book-marking it and checking back regularly!

  2. My developer is trying to persuade me to move to .net
    from PHP. I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type
    on several websites for about a year and am concerned about
    switching to another platform. I have heard good things about
    Is there a way I can transfer all my wordpress posts into it?
    Any help would be really appreciated!

  3. You’re so awesome! I do not believe I’ve truly read through anything like that before. So nice to find someone with a few unique thoughts on this issue. Really.. thanks for starting this up. This web site is one thing that’s needed on the web, someone with a little originality!

Comments are closed.