Lifetime bound on function return type Pin<Box<dyn Future(Output = ()>>>

I have recreated this simple example

I have a register type that has a mapping between a number to a callback function that return a future, the callback function accepts an argument Context, and Context have a lifetime

I want to bound the returned Future to the Context lifetime, since the returned future is only valid as long as the Context is valid, I don't want to make my Context 'static just for it to work

I am not sure if it is possible, how can I make my Callback generic over the Context lifetime

// something like that
type Callback = dyn Fn(Context<'a>) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;

it also doesn't make sense to add a lifetime to the Register type, since it would make the returned Future be bounded to the lifetime of Register and not Context

The surface level solution is

-type Callback = dyn Fn(Context) -> Pin<Box<dyn Future<Output = ()> + Send>>;
+type Callback = dyn Fn(Context<'_>) -> Pin<Box<dyn '_ + Future<Output = ()> + Send>>;

Before the change, you required a closure that could take a Context<'a> with any lifetime 'a and return a Pin<Box<dyn 'static + Future<.... Because

  • Elided and unnamed lifetimes in the arguments of the Fn trait mean "for any lifetime..."[1]
  • But completely elided dyn lifetimes in a Box<..> are 'static

Whether this will be useful in the Tokio runtime, which has many 'static requirements, is another question.


  1. This means I didn't need to add <'_> to the Fn(Context), but it is much clearer if you do so. So I recommend you do so. â†Šī¸Ž

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.