So basically: I have a CPU struct that keeps a VecDeque of boxed closures that get popped and run when the user calls execute on the CPU instance. However, it won't compile.
I get a series of error messages relating to the lifetime of the boxed closure, and it seems to boil down to:
expected `Box<(dyn FnMut() + 'me)>` found `Box<dyn FnMut()>`
I really don't understand why. Shouldn't get_add_two be returning a Box<dyn FnMut() + 'me>?
Each of your closures captures a mutable borrow of the CPU. You can never have multiple mutable references to the same value, so you can never have more than one such closure. Separately, it is also difficult (impossible without the help of unsafe code, and tricky with) to make a self-referential structure, which is what you would have after the push()es.
However, it is easy to rewrite this program to not need either, by passing the CPU into the closures when they're executed, not when they're created:
Don't know why I didn't see that.I think I got so focussed on getting the self capturing by the closures to work that I didn't think twice about he fact that those references are captured for the entire lifetime of the closure. Thanks for making me see the error of my ways.