Q:

Rust program to modify the values of HashMap using the values_mut() method

belongs to collection: Rust HashMap Programs

0

In this program, we will create a HashMap and then we will insert items into HashMap using the insert() function. After that, we will modify the value of HashMap using the values_mut() method and print updated HashMap.

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 modify the values of HashMap using the values_mut() method is given below. The given program is compiled and executed successfully.

// Rust program to modify the values of HashMap 
// using values_mut() method

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

    for val in map.values_mut() {
        *val = *val -50;
    }
    
    println!("HashMap Keys/values:");
    for (key, val) in map.iter() {
        println!("{} -> {}", key, val);
    }
}

Output:

HashMap Keys/values:
Key3 -> 53
Key4 -> 54
Key2 -> 52
Key1 -> 51

Explanation:

Here we created a HashMap. Then we inserted the item into HashMap and modified the value of HashMap using the values_mut() method printed the updated HashMap.

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

total answers (1)

Rust program to modify the values of HashMap using... >>
<< Rust program to print Keys/values of a HashMap usi...