Introduction
The
filter
function in Rust is a powerful and versatile method used to filter elements of an iterator based on a specified predicate. This function is part of the Iterator trait and returns an iterator containing only the elements that satisfy the predicate.
Syntax
fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
Self: Sized,
P: FnMut(&Self::Item) -> bool;
The
filter
function takes a predicate as an argument and returns an iterator. The predicate is a closure that takes a reference to an item and returns a boolean indicating whether the item should be included in the resulting iterator.
Example Usage
Example 1: Filtering even numbers
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let even_numbers: Vec<i32> = numbers.into_iter().filter(|&x| x % 2 == 0).collect();
println!("{:?}", even_numbers); // Output: [2, 4, 6]
}
Example 2: Filtering strings by length
fn main() {
let strings = vec!["short", "a bit longer", "longest"];
let long_strings: Vec<&str> = strings.into_iter().filter(|s| s.len() > 5).collect();
println!("{:?}", long_strings); // Output: ["a bit longer", "longest"]
}
Example 3: Filtering using a custom struct
struct Person {
name: String,
age: u32,
}
fn main() {
let people = vec![
Person { name: String::from("Alice"), age: 30 },
Person { name: String::from("Bob"), age: 20 },
Person { name: String::from("Charlie"), age: 40 },
];
let adults: Vec<&Person> = people.iter().filter(|&p| p.age >= 30).collect();
for person in adults {
println!("{}", person.name);
}
// Output:
// Alice
// Charlie
}
Example 4: Filtering with a mutable predicate
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let mut sum = 0;
let filtered: Vec<i32> = numbers.into_iter().filter(|&x| {
sum += x;
sum <= 10
}).collect();
println!("{:?}", filtered); // Output: [1, 2, 3, 4]
}
Example 5: Filtering optional values
fn main() {
let options = vec![Some(1), None, Some(3), None, Some(5)];
let filtered: Vec<i32> = options.into_iter().filter_map(|x| x).collect();
println!("{:?}", filtered); // Output: [1, 3, 5]
}
Considerations
- The
filter
method consumes the original iterator, so it cannot be used after calling filter
.
See Also
- map - Transforms each element of an iterator using a specified function.
- filter_map - Filters and maps elements of an iterator, discarding None values.
- find - Searches for the first element in an iterator that satisfies a predicate.
- any - Checks if any elements in an iterator satisfy a predicate.
- all - Checks if all elements in an iterator satisfy a predicate.