Iterator Scan Carries Running State

Thread an accumulator through scan so each output derives from prior state, and stop the whole iterator early by returning None.

RustData Integrity

Code

rustsnippet
27 lines
fn main() {
    let readings = [18, 21, 35, 40, 24];

    // scan 携带运行状态:累加器在闭包外持续传递
    let running: Vec<i32> = readings
        .iter()
        .scan(0, |sum, &value| {
            *sum += value;
            Some(*sum)
        })
        .collect();
    println!("running sums: {running:?}");

    // 闭包返回 None 即终止整个迭代:预算用完就停
    let within_budget: Vec<i32> = readings
        .iter()
        .scan(100, |budget, &value| {
            if *budget >= value {
                *budget -= value;
                Some(value)
            } else {
                None
            }
        })
        .collect();
    println!("within budget: {within_budget:?}");
}

Inside the snippet

Iterator Scan Carries Running State is built around the function main.

Putting it to use

Running the file prints labeled results such as running sums:, within budget: — each operation’s effect is visible in the output.

Core lines

.scan(100, |budget, &value| {
if *budget >= value {
*budget -= value;
Some(value)
} else {
None
}
})
.scan(0, |sum, &value| {
*sum += value;
Some(*sum)
})

Interactive Tools for This Topic

FAQ

What does Iterator Scan Carries Running State print when run?
The script runs standalone; its 2 labeled outputs include `running sums:`, `within budget:`.