Home »
Rust »
Rust Programs
Rust program to demonstrate the take() method of HashSet
Rust | HashSet Example: Write a program to demonstrate the take() method of HashSet.
Submitted by Nidhi, on October 14, 2021
Problem Solution:
In this program, we will create a HashSet and demonstrate the use of the take() method. The take() method removes and returns the value in the set, if any, that is equal to the given one.
Program/Source Code:
The source code to demonstrate the take() method of HashSet is given below. The given program is compiled and executed successfully.
// Rust program to demonstrate the
// take() method of HashSet
use std::collections::HashSet;
fn main() {
let mut set: HashSet<_> = [10, 20, 30,40,50].iter().cloned().collect();
let mut num:i32=20;
println!("HashSet before take(): \n{:?}", set);
set.take(&num);
println!("HashSet after take(): \n{:?}", set);
}
Output:
HashSet before take():
{10, 20, 50, 30, 40}
HashSet after take():
{10, 50, 30, 40}
Explanation:
Here, we created a HashSet with 5 integer elements. Then we remove a given item using the take() method from HashSet and print the result.
Rust HashSet Programs »