To remove items from a set based on a condition in Rust, you can use the retain
method, which allows you to keep only the elements that satisfy a given predicate.
In this example,
use std::collections::HashSet;
.HashSet<i32>
named number_set
and initialize it with the values [1, 2, 3, 4, 5].iter().cloned().collect()
.retain
method with a lambda function to define the condition for removing elements. The lambda function |&x| x % 2 != 0
keeps only the odd numbers in the set.use std::collections::HashSet;
fn main() {
let mut number_set: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();
number_set.retain(|&x| x % 2 != 0);
for num in &number_set {
print!("{} ", num);
}
println!();
}
1 3 5
In this example,
use std::collections::HashSet;
.HashSet<String>
named string_set
and initialize it with the values ["apple", "banana", "cherry", "date", "grape"].iter().cloned().map(String::from).collect()
.retain
method with a lambda function to define the condition for removing elements. The lambda function |s| s.len() >= 6
keeps only the strings with a length of 6 or more characters.use std::collections::HashSet;
fn main() {
let mut string_set: HashSet<String> = ["apple", "banana", "cherry", "date", "grape"].iter().cloned().map(String::from).collect();
string_set.retain(|s| s.len() >= 6);
for str in &string_set {
print!("{} ", str);
}
println!();
}
banana cherry
In this tutorial, we learned How to Remove Items from Set based on a Condition in Rust language with well detailed examples.