w3resource

Rust HashMap Key-Value Update & Printing

Rust Arrays: Exercise-5 with Solution

Write a Rust program to update the value associated with a key in a HashMap and print the updated HashMap.

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);

    // Print the original HashMap
    println!("Original HashMap: {:?}", my_map);

    // Define the key for which to update the value
    let key_to_update = "b";
    let new_value = 42; // New value to assign to the key

    // Update the value associated with the key in the HashMap
    match my_map.get_mut(key_to_update) {
        Some(value) => *value = new_value, // If the key exists, update the value
        None => println!("Key '{}' does not exist in the HashMap.", key_to_update), // If the key does not exist, print a message
    }

    // Print the updated HashMap
    println!("Updated HashMap: {:?}", my_map);
}

Output:

Original HashMap: {"c": 3, "b": 2, "a": 1}
Updated HashMap: {"c": 3, "b": 42, "a": 1}

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.
  • println!("Original HashMap: {:?}", my_map);: This line prints the original HashMap before any updates are made.
  • let key_to_update = "b";: This line defines the key for which we want to update the associated value in the HashMap.
  • let new_value = 42;: This line defines the new value that we want to assign to the key in the HashMap.
  • match my_map.get_mut(key_to_update) { ... }: This line attempts to retrieve a mutable reference to the value associated with the specified key from the HashMap using the "get_mut()" method. The "match" statement is used to handle the result:
    • If the key exists (Some(value)), it updates the value associated with the key to the new value (*value = new_value).
    • If the key does not exist (None), it prints a message indicating that the key does not exist in the HashMap.
  • println!("Updated HashMap: {:?}", my_map);: This line prints the updated HashMap after the value associated with the specified key has been updated.

Rust Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/collections_and_data_structures/rust-hashmaps-exercise-5.php