Как отметил Робин Зигмонд в комментариях, вам, вероятно, нужна функция Iterator::scan
.
Пример:
/// Our "event" type, with increment and decrement events.
#[derive(Debug)]
enum Event {
Inc,
Dec,
}
/// For simplicity, the `Event::apply` function will modify our integer
/// depending on the event.
impl Event {
fn apply(&self, n: i32) -> i32 {
match self {
Inc => n + 1,
Dec => n - 1,
}
}
}
/// Import `Event::Inc` and `Event::Dec` into scope so we can access them as
/// simply `Inc` and `Dec`.
use Event::{Inc, Dec};
fn main() {
// List of events
let events = &[ Inc, Inc, Dec, Inc, Dec, Dec ];
let values: Vec<_> = events.iter().scan(0i32, |n, ev| {
// `n` is a mutable reference to the "state" of the scan.
// It initially has the value `0i32`, but we can modify it each time
// the closure is called.
*n = ev.apply(*n);
// The closure can return `Some(expr)`, which is the next value of the
// iterator, or `None` to end early. In our case we just return the state.
Some(*n)
}).collect();
println!("events = {:?}", events); // [Inc, Inc, Dec, Inc, Dec, Dec]
println!("values = {:?}", values); // [1, 2, 1, 2, 1, 0]
}
Пример детской площадки