Q:

Rust program to get value using Specified key in HashMap

belongs to collection: Rust HashMap Programs

0

In this program, we will create a HashMap and then we will get value using the specified key in the get() method of HashMap and print the result.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to get value using the Specified key in HashMap is given below. The given program is compiled and executed successfully.

// Rust program to get value 
// using Specified key in HashMap

use std::collections::HashMap;

fn main() 
{
    let mut map = HashMap::new();
    
    map.insert("Key1", 101);
    map.insert("Key2", 102);
    map.insert("Key3", 103);
    map.insert("Key4", 104);

    match map.get(&"Key2") {
      Some(&number) => println!("Value: {}", number),
      _ => println!("Specified key is not found."),
    }
}

Output:

Value: 102

Explanation:

Here, we created a HashMap. Then we got the value using the specified key in the get() method of HashMap and printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to remove an item from HashMap using ... >>
<< Rust program to check the given HashMap is empty o...