Q:

Rust program to remove an item from HashSet

belongs to collection: Rust HashSet Programs

0

In this program, we will create a HashSet to store integer items, and then we will add and remove items from the HashSet.

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 find the length of HashSet is given below. The given program is compiled and executed successfully.

// Rust program to remove an item 
// from HashSet

use std::collections::HashSet;
use std::io;

fn main() {
    let mut set:HashSet<i32> = HashSet::new();
    let mut item:i32=0;
    let mut input = String::new();

    set.insert(10);
    set.insert(20);
    set.insert(30);
    set.insert(40);
    set.insert(50);
    
    println!("HashSet before removing item: \n{:?}",set);
    
    println!("Enter Item: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    item = input.trim().parse().expect("Not a valid number");
    
    set.remove(&item);
    
    println!("HashSet after removing item: \n{:?}",set);
}

Output:

HashSet before removing item: 
{20, 10, 40, 50, 30}
Enter Item: 
40
HashSet after removing item: 
{20, 10, 50, 30}

Explanation:

Here, we created a HashSet to store integer elements. Then we added items using the insert() method and removed the item from HashSet using the remove() method. After that, we printed updated HashSet.

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

total answers (1)

Rust program to check an item contains in HashSet ... >>
<< Rust program to find the length of HashSet...