Lifetime bounds to use for Future that isn't supposed to outlive calling scope

I’ve written answers on similar problems in the past. E.g. here or here and the second one links some more places.

It’s possible to avoid the need for Box using trait, and @vague above provided an example, too, but those will unfortunately (for no good reason) not work with closures, only with (async) fn items. In that sense, the BoxFuture approach is more flexible/easy to use, at the minor downside of adding an allocation and some dynamic function calls.

(For example in both @vague's and @quinedot's playgrounds, you cannot write something like .dispatch_request(|x: &mut String| test_interpreter(x)) without incomprehensible and unavoidable compilation errors; so in particular, you can never pass a callback that needs to actually capture some data.)

3 Likes