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

Rust | HashMap Program: Write a program to remove an item from HashMap using the remove () method.
Submitted by Nidhi, on October 17, 2021

Problem Solution:

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.

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.

Rust HashMap Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.