3
fn hello<'a>() {}

In rust, can a function have its own lifetime? I ran into a piece of code as below

struct Hi {}

async fn wrapper<'a, F, Fut>(f: F) 
where 
Fut: Future<Output = ()>,
F: FnOnce(&'a mut Hi) -> Fut{

}

but couldn't understand what lifetime 'a could mean here...

pandawithcat
  • 571
  • 2
  • 13
  • 1
    the lifetime is not for the function, but for the argument of its argument here, namely "Hi". – Adam Mar 17 '21 at 07:02
  • 1
    Does this answer your question? [Why does the lifetime name appear as part of the function type?](https://stackoverflow.com/questions/29837398/why-does-the-lifetime-name-appear-as-part-of-the-function-type) – kmdreko Mar 17 '21 at 08:07

1 Answers1

3

can a function have its own lifetime?

Functions don't have lifetimes; references do. But you can have a reference to a function. And you can have a lifetime as a parameter of a function.

couldn't understand what lifetime 'a could mean here.

It just means it's a mutably borrowed parameter of closure with lifetime &'a.

In essence, async fn wrapper<F, Fut>(f: F) behaves the same, since &' a can be elided.

It would be useful if, somewhere inside the function's code, you needed to say lifetime 'a will outlive some lifetime 'b.

For example:

async fn wrapper<'a, 'b, F, Fut>(f: F, b: &'b Hi)
where
    Fut: Future<Output = ()>,
    F: FnOnce(&'a mut Hi) -> Fut,
    'a : 'b
Daniel Fath
  • 16,453
  • 7
  • 47
  • 82