Earth Engine
Earth Engine

Reputation: 10436

Is it possible to specify the lifetime of async function's result?

We can write the following

fn foo<'a, 'b>(va: &'a (), vb: &'b ()) -> impl std::future::Future<Output = ()> + 'b {
    async {}
}

without using the async keyword. Can we do the same with the async keyword?

We usually write

async fn foo<'a, 'b>(va: &'a (), vb: &'b ()) {
    async {}
}

But there is no where I can put the output lifetime 'b.

An example provided by a commentator Kitsu

Playground

use std::cell::RefCell;

fn foo<'a, 'b>(va: &'a i32, vb: &'b RefCell<i32>) -> impl std::future::Future<Output = i32> + 'b {
    let mut t = vb.borrow_mut();
    *t += va;
    let x = *t;
    async move { x }
}

Upvotes: 0

Views: 572

Answers (1)

Kornel
Kornel

Reputation: 100110

async fn always automatically depends on all lifetimes from its arguments.

There's no syntax to change it, because there's no other possibility. That's because calling async fn doesn't run any code from the function body, but only stores function's arguments in the Future it returns. The future will later use the arguments when it's polled, so it's tied to all the lifetimes of all arguments.

Upvotes: 2

Related Questions