HashMap in Rust Programming


HashMap is an important data structure, as it allows us to store data in key-value pairs. In Rust, HashMap stores values by key.

HashMap keys can be Boolean, Integer, strings or any other data type that implements the Eq and Hash traits.

HashMaps can grow in size, and when the space becomes too excessive, they can also shrink themselves.

We can create a HashMap in multiple ways, we can use either HashMap::with_capacity(uint) or HashMap::new().

Following are the methods that HashMaps support:

  • insert()
  • get()
  • remove()
  • iter()

Example

Let’s see an example where we build a HashMap and use all these operations stated above.

Consider the example shown below.

 Live Demo

use std::collections::HashMap;

fn call(number: &str) -> &str {
   match number {
      "798-133" => "We're sorry. Please hang up and try again.",
      "645-7698" => "Hello, What can I get for you today?",
      _ => "Hi! Who is this again?"
   }
}
fn main() {
   let mut contacts = HashMap::new();
   contacts.insert("Mukul", "798-133");
   contacts.insert("Mayank", "645-7698");
   contacts.insert("Karina", "435-8291");
   contacts.insert("Rahul", "956-1745");
   match contacts.get(&"Mukul") {
      Some(&number) => println!("Calling Mukul: {}", call(number)),
      _ => println!("Don't have Mukul's number."),
   }
   // `HashMap::insert()` returns `None`
   contacts.insert("Mukul", "164-6743");
   match contacts.get(&"Mayank") {
      Some(&number) => println!("Calling Mayank: {}", call(number)),
      _ => println!("Don't have Mayank's number."),
   }
   contacts.remove(&"Mayank");
   // `HashMap::iter()` returns an iterator that yields
   // (&'a key, &'a value) pairs in arbitrary order.
   for (contact, &number) in contacts.iter() {
      println!("Calling {}: {}", contact, call(number));
   }
}

Output

Calling Mukul: We're sorry. Please hang up and try again.
Calling Mayank: Hello, What can I get for you today?
Calling Mukul: Hi! Who is this again?
Calling Karina: Hi! Who is this again?
Calling Rahul: Hi! Who is this again?

Updated on: 03-Apr-2021

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements