fold carries an accumulator through every item that reaches the end of an iterator pipeline.

Program

Play the program to choose whether zero readings should count as included readings.

fold_count.rs
fn main() {
    let include_zero = ;
    let readings = [3, 0, 4];
    let count = readings.iter().copied().filter(|value| include_zero || *value != 0).fold(0, |acc, _value| acc + 1);
    println!("count={count}");
}
fn main() {
    let include_zero = ;
    let readings = [3, 0, 4];
    let count = readings.iter().copied().filter(|value| include_zero || *value != 0).fold(0, |acc, _value| acc + 1);
    println!("count={count}");
}
lazy pipeline The filter and fold stages run only when the final count is requested.
fold `fold(0, |acc, _value| acc + 1)` increments the accumulator for each included item.
predicate `include_zero || *value != 0` changes which values reach the fold.