w3resource

Rust HashMap Key existence Check & Message printing

Rust Arrays: Exercise-3 with Solution

Write a Rust program that checks if a key exists in a HashMap and print a corresponding message.

Sample Solution:

Rust Code:

use std::collections::HashMap; // Import the HashMap type from the standard library

fn main() {
    // Create a HashMap to store key-value pairs
    let mut my_map: HashMap<&str, i32> = HashMap::new(); // Key: &str (string slice), Value: i32

    // Insert some key-value pairs into the HashMap
    my_map.insert("a", 1);
    my_map.insert("b", 2);
    my_map.insert("c", 3);

    // Define the key to check for existence
    let key_to_check = "b";

    // Check if the key exists in the HashMap
    if my_map.contains_key(key_to_check) {
        println!("Key '{}' exists in the HashMap.", key_to_check);
    } else {
        println!("Key '{}' does not exist in the HashMap.", key_to_check);
    }
}

Output:

Key 'b' exists in the HashMap.

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::collections::HashMap;: This line imports the "HashMap" type from the standard library, allowing us to use HashMaps in our code.
  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let mut my_map: HashMap<&str, i32> = HashMap::new();: This line creates an empty HashMap named 'my_map' with keys of type '&str' (string slice) and values of type i32.
  • my_map.insert("a", 1);: This line inserts a key-value pair into the 'my_map' HashMap, where the key is the string slice "a" and the value is the integer 1. Similar lines insert additional key-value pairs.
  • let key_to_check = "b";: This line defines the key that we want to check for existence in the HashMap.
  • if my_map.contains_key(key_to_check) { ... }: This line checks if the key specified by key_to_check exists in the HashMap using the "contains_key()" method. If the key exists, it executes the code block inside the if statement; otherwise, it executes the code block inside the else statement.
  • println!("Key '{}' exists in the HashMap.", key_to_check);: This line prints a message indicating that the key exists in the HashMap if the condition in the if statement evaluates to true.
  • println!("Key '{}' does not exist in the HashMap.", key_to_check);: This line prints a message indicating that the key does not exist in the HashMap if the condition in the if statement evaluates to false.

Rust Code Editor:

Previous: Rust HashMap Iteration: Printing Key-Value pairs.
Next: Rust HashMap Key Value Retrieval & Printing.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.