Count with filter().count()
Write a Rust function that takes a vector of integers and returns the count of even numbers using an iterator chain with .iter(), .filter(), and .count(). The count() method consumes the iterator and returns the number of elements that passed through the filter.
The iterator chain .iter().filter(|&&x| x % 2 == 0).count() is a concise and idiomatic Rust pattern. .iter() creates an iterator over references to the elements, .filter() keeps only elements matching the closure, and .count() consumes the iterator and returns the total. This functional approach is preferred over manual loops with counters in idiomatic Rust.
The count() method is a consuming adapter that iterates through all remaining elements and returns their count. It works on any iterator, not just filtered ones. After calling count(), the iterator is consumed and cannot be used again. This is an example of Rust's ownership system at work in the iterator API.
Time complexity is O(n) where n is the vector length, as each element must be checked by the filter. Space complexity is O(1) as no intermediate collection is created. The iterator chain is lazy: filter runs only as many elements as needed by count, but count needs all elements so every element is checked.
Edge cases include empty vectors (returns 0), all elements passing the filter (returns the vector length), no elements passing (returns 0), and negative numbers which are correctly handled by the modulo operator.
Example Input & Output
No evens
All even
Evens: -2, 0, 2
Three even numbers: 2,4,6
Empty vector
Algorithm Flow

Solution Approach
Best Answers
fn solution(nums: Vec<i32>) -> usize {
nums.iter().filter(|&&x| x % 2 == 0).count()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
