Are the lifetimes necessary?


I've written a crate to run coroutines as a data driven data structure. However when it comes to providing the 'continuation' or 'resume when fed a new input', my implementation of 'bind' from a monad point of view gets pretty lifetimey pretty quickly.

bicoro/ at main · btrepp/bicoro · GitHub

I'm wondering if there is a way of writing this without the lifetimes?.
I'm also wondering if there is a way to write without the Box as much, I think it is required, but would be nice if there was progressive enhancement, eg if you had a dumb fn pointer it would work in a no-std context, but you can use Box if you run in std and have an allocator.

Appreciate any pointers on the heap and lifetimes, I've sort of 'fought the compiler until it compiles', and the code works for the use-cases I had, but I feel like it isn't expressed correctly, so maybe is more difficult to read than it needs to be.

Thanks :slight_smile:

Well, do you want it to be possible for the Box<dyn FnOnce ...> to contain any references to local variables? If you do want that to be possible, then you do need the lifetime, and the lifetime becomes the duration in which the value in the box borrows from those local variables.

The caller can set the lifetime to 'static if the FnOnce closure doesn't contain any references.

If you don't want to allow references inside the closure, then you can simply remove the lifetimes. (And put : 'static on all types that go inside the box.)

1 Like