rust filtering a vector example
Filtering a Vector in Rust
To filter a vector in Rust, you can use the iter()
method to create an iterator over the vector's elements, and then use the filter()
method to apply a predicate to each element. The filter()
method returns a new iterator that only yields the elements for which the predicate returns true
. Finally, you can collect the filtered elements into a new vector using the collect()
method.
Here's an example of how to filter a vector in Rust:
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let filtered_numbers: Vec<_> = numbers.iter().filter(|&x| *x % 2 == 0).collect();
println!("{:?}", filtered_numbers);
}
In this example, we have a vector numbers
containing the numbers 1 to 6. We use the iter()
method to create an iterator over the vector's elements. Then, we use the filter()
method with a closure that checks if each element is divisible by 2 (*x % 2 == 0
). The closure takes a reference to each element (&x
) and returns true
if the element is divisible by 2. The filter()
method returns a new iterator that only yields the elements that satisfy the predicate.
Finally, we use the collect()
method to collect the filtered elements into a new vector (filtered_numbers
). The collect()
method consumes the iterator and collects its elements into a collection type specified by the type annotation (Vec<_>
in this case).
The output of the above code will be [2, 4, 6]
, which are the even numbers from the original vector.
I hope this helps! Let me know if you have any further questions.