Q:

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

belongs to collection: Rust HashMap Programs

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)

Rust program to check a HashMap contains a specifi... >>
<< Rust program to get value using Specified key in H...