Q:

Rust program to remove an item from HashMap using remove () method

0

In this program, we will create a HashMap and insert some items into it. Then we remove an item using the remove() method based on a specified key.

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 remove an item from HashMap using the remove() method is given below. The given program is compiled and executed successfully.

// Rust program to remove an item 
// from the HashMap using the 
// remove() 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);

    println!("HashMap before remove: \n{:?}",map);
    map.remove("Key3");
    println!("HashMap after remove: \n{:?}",map);
}

Output:

HashMap before remove: 
{"Key3": 103, "Key4": 104, "Key1": 101, "Key2": 102}
HashMap after remove: 
{"Key4": 104, "Key1": 101, "Key2": 102}

Explanation:

Here, we created a HashMap. Then we inserted some items into it. After that, we removed an item from HashMap using the remove() method based on a specified key and printed the updated HashMap.

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now