Applied Intermediate

12  Iterators

Iterator chains replace most hand-written loops. Build a value by chaining adaptors and finishing with a consumer like sum or collect.

Step 1 / 3

In sum_even_squares, keep the even numbers, square them, and sum the result -- as one iterator chain.

Hints
  • Chain it: .iter(), then .filter(..), then .map(..), then .sum().
  • iter() over a slice yields references, so the closures see &&i32 / &i32.
12_iterators.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
fn sum_even_squares(nums: &[i32]) -> i32 {
    nums.iter().filter(|&&n| n % 2 == 0).map(|&n| n * n).sum()
}