To filter elements of an array based on a condition in Rust, you can use iterators along with filter and collect methods.
In this example,
numbers
containing integers.even_numbers
.fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let even_numbers: Vec<_> = numbers.into_iter().filter(|&n| n % 2 == 0).collect();
println!("Even Numbers: {:?}", even_numbers);
}
Even Numbers: [2, 4, 6, 8, 10]
In this example,
words
containing strings.filtered_words
.fn main() {
let words = vec!["apple", "banana", "cherry", "date", "fig"];
let filtered_words: Vec<_> = words.into_iter().filter(|&word| word.len() > 5).collect();
println!("Filtered Words: {:?}", filtered_words);
}
Filtered Words: ["banana", "cherry"]
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Rust language with well detailed examples.