Rust Program to Update value of HashMap using key


Update value of HashMap using key

Rust Programming Language


Update value of HashMap using key


Problem


Rust program that updates the value of a HashMap using its key.

Input


use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    
    // Add some key-value pairs to the map
    map.insert("apple", 3);
    map.insert("banana", 2);
    map.insert("orange", 5);
    
    // Print the initial values of the map
    println!("Before update: {:?}", map);
    
    // Update the value of the "apple" key to 5
    *map.get_mut("apple").unwrap() = 5;
    
    // Print the updated values of the map
    println!("After update: {:?}", map);
}{codeBox}

Output


Before update: {"orange": 5, "apple": 3, "banana": 2}
After update: {"orange": 5, "apple": 5, "banana": 2}{codeBox}

Explanation


In this example, we create a new HashMap and insert some key-value pairs. Then, we print the initial values of the map.

To update the value associated with the key "apple", we use the get_mut method to get a mutable reference to the value, and then update it using the dereference operator *. If the key is not present in the map, get_mut will return None, so we use the unwrap method to panic if this happens (in a real program, you would want to handle this case more gracefully).

Finally, we print the updated values of the map.

The Before update: line shows the initial values of the HashMap, with the keys and values in an arbitrary order. The After update: line shows the updated values of the HashMap, with the keys and values in an arbitrary order.


Post a Comment