Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does lifetime without a variable attached mean?

Tags:

rust

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...

like image 736
pandawithcat Avatar asked Feb 16 '26 00:02

pandawithcat


1 Answers

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
like image 181
Daniel Fath Avatar answered Feb 20 '26 01:02

Daniel Fath