HashMap in Rust

HashMap in Rust is nothing, but a collection in rust, which uses a look-up table using a key-value pair to store and retrieve data. A hashmap has to be explicitly imported from the Rust inbuilt library collection before it can be used inside a program.

A hashmap stores data or values which is called hash table. It may be noted that hashmap is a structure can be used by including the collection name inside the program- use std::collections::HashMap; at the beginning of any program which uses the hashmap.

The key is like a pointer for the original data in the hashmap. The keys are used to use the look-up table to search a particular data corresponding to the key. The hashmap structure is defined in the module std::collections.

Steps for a HashMap
  • Importing the Rust inbuilt collection- HashMap modules.
  • Creating an instance inside the program for the HashMap.
  • Using HashMap functions to perform an operation (insertion, remove, iter, etc)
  • Execute the code.

A program to insert some data in the hashmap :

use std::collections::HashMap; // importing the libraries
fn main() {
 let mut department = HashMap::new(); // creating the instance
 department.insert("CSE", "Computer Science And Engineering"); // first initialization
 department.insert("IT", "Information Technology"); //second initialization
 department.insert("ME", "Mechanical engineering"); //third initialization
 println!("{:?}", department); //printing the hashmap instance
}

In the above program, an hashmap instance called department is created. Then the macro insert() is used to insert the data into the hasmap stack along. The hashmap contents can be directly printed using the macro println!().

Program Output :

rust-hashmap-example

Mostly Used Library Functions in Rust

There are different functions in the Rust library which are useful in the implementation of the Rust HashMap. Below are the list of the functions which are used frequently:

  • insert() : This function inserts a value along with the corresponding key into the HashMap. Usually, the key along with the value is called key-value pair.
  • len() : This function returns the length of a HashMap, which is directly the number of elements in a HashMap.
  • get() : This function returns the reference of the value which is pointerd by the key.
  • iter():
  • contains_key() :
  • remove() :

Program using the insert() function

Syntax :

HashMap_instance_name.insert("key","value");

Program to insert some key-value pair and display the contents :

use std::collections::HashMap; // importing the libraries
fn main() {
 let mut department = HashMap::new(); // creating the instance
 department.insert("CSE", "Computer Science And Engineering"); // first initialization
 department.insert("IT", "Information Technology"); //second initialization
 department.insert("ME", "Mechanical engineering"); //third initialization
 println!("{:?}", department); //printing the hashmap instance
}

In the above program, an hashmap instance called department is created. Then the macro insert() is used to insert the data into the hasmap stack along. The hashmap contents can be directly printed using the macro println!().

Program Output :

rust-hashmap-example

Program using len()

Syntax:

HashMap_instance_name.len()

A program to print the length(no of elements) in a HashMap.

use std::collections::HashMap; // importing the libraries
fn main() {
 let mut department = HashMap::new(); // creating the instance
 department.insert("CSE", "Computer Science"); // first initialization
 department.insert("IT", "Information Technology"); //second initialization
 department.insert("ME", "Mechanical engineering"); //third initialization
 println!("The number of contents or the length of the HashMap is{:?}", department.len()); //printing the hashmap length
}

In the above program, we have inserted three key-value pair and then tried to retreive the length of the Hashmap using the len() function:

 println!("The number of contents or the length of the HashMap is{:?}", department.len());

Program Output :

rust-hashmap-length

Program Using the get()

This has to keep in mind that the get() function will return the reference of the value which is pointed by the key.

Now to sense the returned reference, we need to use the match operator. If there is a referene returned then the Some part will execute otherwise the None part will execute.

match instance_name.get( & "key") {
 Some(variable) => {
  //some code
 }
 None => {
  // some code
 }
}

A program to get a specific value from a HashMap corresponding to a particular key.

use std::collections::HashMap; // importing the libraries
fn main() {
 let mut department = HashMap::new(); // creating the instance
 department.insert("CSE", "Computer Science"); // first initialization
 department.insert("IT", "Information Technology"); //second initialization
 department.insert("ME", "Mechanical engineering"); //third initialization

 match department.get( & "IT") {
  Some(value) => {
   println!("The value returned by the key IT is: {}", value);
  }
  None => {
   println!("nothing found");
  }
 }
}

Program Output :

rust-hashmap-get

Printing the reference directly

This is very interesting to note that, the reference of the value in the hashmap can be directly assigned to a variable, and then can be printed.

Note: Even when we assign the get() return value directly to a variable, still the Rust compiler uses the match operator and methods- Some and None are invoked by default.

For thus, we have to just declare a variable and assign it the returned reference of the get() function.

Syntax :

let variable_name= instance_name.get(&"key");

Now as per the syntax above, the referenced value corresponding to the key, from the hashmap instance - instance_name will be assigned to the variable- variable_name, which can be printed directly.

A program to print value corresponding to a key (When value matches)

use std::collections::HashMap;
fn main() {
 let mut department = HashMap::new();
 department.insert("CSE", "Computer Science");
 department.insert("IT", "Information Technology");
 department.insert("ME", "Mechanical engineering");
 let num = department.get( & "CSE");
 println!("{:?}", num);

}

In the above program, reference returned from the get() method is directly copied to the variable num. Now when we want to print the num variable which now does not contain the data but the reference of the data, the match operator comes into action in the background.

So, if the key mentioned inside the get() refers a data of the hashmap (When the key has a corresponding value, then the Some() method will execute, displaying the value itself.

Otherwise, None (which means Null), will be executed.

Program Output:

rust-hashmap-get-variable-match

A program to print value corresponding to a key (When value does not match)

use std::collections::HashMap;
fn main() {
 let mut department = HashMap::new();
 department.insert("CSE", "Computer Science");
 department.insert("IT", "Information Technology");
 department.insert("ME", "Mechanical engineering");
 let reference = department.get( & "ECE");
 println!("{:?}", reference);
}

In the above program, we have mentioned department name -ECE, inside the get(), which does not exist in the HashMap, and a Null value is returned.

Program Output :

rust-hashmap-get-variable-no-match

As seen the program output, since branch name mentioned here does not matche, therefore None is returned.

Program Using the iter() function

The iter() function is used to return all the key-value pairs in a HashMap. The for loop with a custom syntax can be used to iterate and retrieve all the key-value pairs of the HashMap instance.

Syntax :

 for (key, val) in instance_name.iter() {
      println!("{} {}", key, val);
   }

The keyword key and val are the default keywords for the Key and Value of the HashMap. The code line- for (key, val) in instance_name.iter() means that, that for every key-value pair the iter() function should iterate.

Note: It should be noted that, the retrieval of the key-value pair is arbitrary.

In the below program we shall initialize an instance with three key value pair and use the iter() function, to print all the key-value pairs.

A program to display all key-value pairs in a HashMap :

use std::collections::HashMap;
fn main() {
 let mut department = HashMap::new();
 department.insert("CSE", "Computer Science");
 department.insert("IT", "Information Technology");
 department.insert("ME", "Mechanical engineering");

 for (key, val) in department.iter() {
  println!("key: {} val: {}", key, val);
 }
}

In the above program we have seen that, all the values are inserted into the instance of the hashmap. Now we have used the for and used the iter() function with the instance name to get all the key-value pair.

Program Output :

rust-hashmap-iter

In the above output, we can see that all the contents of the HashMap instance is printed. Now it may be noted that, the order of display of the contents in output is not the same as the order of initialization.

We know that the order of initialization was CSE -> IT -> ME. But in the output, it came as: CSE->ME->IT. It means that the key-value pair which is iterated is done arbitrarily.

Program Using contains_key()

The function contains_key(), returns a true, if the key is matched or is present inside the HashMap. To sense whether the function contains_key(), returns a true, therefore, we use a if statement for it.

Syntax :

if instance_name.contains_key( & "key") {
 //some code
}

Program to check whether a key-value pair exists inside a program :

use std::collections::HashMap;
fn main() {
 let mut department = HashMap::new();
 department.insert("CSE", "Computer Science");
 department.insert("IT", "Information Technology");
 department.insert("ME", "Mechanical engineering");

 if department.contains_key( & "ME")
 {
  println!("This department is present in the HashMap");
 }
}

In the above program, we have have created the instance called department and initialized it with three key-value pair. And then using the contains_key() function, we checked whether the function returns a true when the reference for the key is passed as parameter inside it.

Program Output :

rust-hashmap-contain

Program Using the remove()

The function remove() can remove or delete a key-value pair form the HashMap. This is one of the beauty of the HashMap, that we can directly delete a key-value pair from it, at the time of execution itself.

Syntax :

instance_name.remove( & "key");

Program to remove a key-value pair

use std::collections::HashMap;
fn main() {
 let mut department = HashMap::new();
 department.insert("CSE", "Computer Science");
 department.insert("IT", "Information Technology");
 department.insert("ME", "Mechanical engineering");
 if department.contains_key( & "ME") {
  println!("This department ME is present in the HashMap");
 }
 department.remove( & "ME");
 println!("After Removing");
 if department.contains_key( & "ME") {
  println!("This department ME present in the HashMap");
 }
 else {
  println!("The department ME is not present in the HashMap now");
 }
}

In the above program, we have initialized the instance- department with three key-value pair. And used the function remove() to remove one key-value pair.

And then using an if statement we have check whether the key-value pair has been removed from the HashMap.

Program Output :

rust-hashmap-remove









Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions