Closures have some data in their state, but how do I make it mutable? For example, I want a counter closure which returns the incremented value each time, but it doesn't work. How do I make it work?
fn counter() -> Box<Fn() -> i32> {
let mut c: i32 = 0;
Box::new(move || {
c += 1;
c
})
}
fn main() {
let mut a = counter();
let mut b = counter();
println!("{:?}", [a(), a(), a(), b(), b(), a()]);
}
Error (and warning) I'm getting:
error: cannot assign to captured outer variable in an `Fn` closure
c += 1;
^~~~~~
help: consider changing this closure to take self by mutable reference
Box::new(move || {
c += 1;
c
})
I expect it to output something like [1, 2, 3, 1, 2, 4].