 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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?
Advertisements
 