To filter items of a set based on a condition in Rust, you can use iterators and closures with the filter method to create a new set from the filtered items.
In this example,
number_set
using the hashset!
macro from the hashbrown
crate, which contains integer values 1
, 5
, 10
, 15
, and 20
.iter()
method to create an iterator over number_set
and chain it with the filter
method, which takes a closure as the filtering condition to filter numbers greater than 5.filtered_set
.filtered_set
and print each filtered item to the console.use hashbrown::HashSet;
fn main() {
let number_set = hashset!{1, 5, 10, 15, 20};
let filtered_set: HashSet<i32> = number_set.iter().filter(|&num| *num > 5).copied().collect();
for num in &filtered_set {
println!("{}", num);
}
}
10 15 20
In this example,
string_set
using the hashset!
macro from the hashbrown
crate, which contains string values "apple"
, "banana"
, "cherry"
, "date"
, and "grape"
.iter()
method to create an iterator over string_set
and chain it with the filter
method, which takes a closure as the filtering condition to filter strings containing the letter 'a'.filtered_string_set
.filtered_string_set
and print each filtered string to the console.use hashbrown::HashSet;
fn main() {
let string_set = hashset!{"apple", "banana", "cherry", "date", "grape"};
let filtered_string_set: HashSet<&str> = string_set.iter().filter(|&str| str.contains('a')).copied().collect();
for str in &filtered_string_set {
println!("{}", str);
}
}
apple banana grape
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Rust language with well detailed examples.