To remove a specific item from a set in Rust, you can use the remove method to delete the item from the set.
In this example,
number_set
using the HashSet
type from the Rust Standard Library, which contains integer values 1
, 2
, 3
, 4
, and 5
.remove
method of number_set
to remove the item 3
from the set.number_set
to see the removed item.use std::collections::HashSet;
fn main() {
let mut number_set: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();
number_set.remove(&3);
println!("{:?}", number_set);
}
{1, 2, 4, 5}
In this example,
string_set
using the HashSet
type from the Rust Standard Library, which contains string values "apple"
, "banana"
, "cherry"
, "date"
, and "grape"
.remove
method of string_set
to remove the item "cherry"
from the set.string_set
to see the removed item.use std::collections::HashSet;
fn main() {
let mut string_set: HashSet<&str> = ["apple", "banana", "cherry", "date", "grape"].iter().cloned().collect();
string_set.remove("cherry");
println!("{:?}", string_set);
}
{"apple", "banana", "date", "grape"}
In this tutorial, we learned How to Remove Specific Item from a Set in Rust language with well detailed examples.