How to retrieve the last state from scan?

Iterator::scan has the following function signature:

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>ⓘ
where
    Self: Sized,
    F: FnMut(&mut St, Self::Item) -> Option<B>

We can use it like:

#[derive(Debug)]
struct State(i32);

fn main() {
    let v = vec![1,2,3,4];
    let state = State(0);
    let u: Vec<i32> = v.iter().scan(state, |s, i| {
        s.0 = s.0 + i;
        Some(s.0)
    }).collect();
    println!("{:?}", u);
}

How can I retrieve the final state after the Scan is cosumed by the method collect?

You can capture a mutable reference instead of the struct:

-    let state = State(0);
+    let mut real_state = State(0);
+    let /* borrowed_ */ state = &mut real_state;
     let u: Vec<i32> = v.iter().scan(state, |s, i| {
         s.0 = s.0 + i;
         Some(s.0)
     }).collect();
     println!("{:?}", u);
+    println!("{:?}", real_state);
1 Like

At this point you can just use map instead of scan (technically the correct alternative would be map_while, but map also works if you never return None)

1 Like