Async lifetime

Migo·2024년 2월 25일
0

Fluent Rust

목록 보기
18/20
post-thumbnail

Problem

Most of your functions that's either "colored" with async or returns impl Future will return the result right away instead of delegating the returning part to another async function as follows.

async fn func_returning_u8()->u8{
	...
}

If your async function starts taking references or non-'static argument and returns yet another awaitable, it begins to make some trouble as the lifetime signature will become something along the lines:

// The following function takes reference to u8 and it
async fn foo(x: &u8) -> u8 { *x }

// is equivalent to this function:
fn foo_with_lifetime_specified<'a>(x: &'a u8) -> impl Future<Output = u8> + 'a {
    async move { *x }
}

So, the following starts error out:

fn func_that_envokes_yet_another_async()->impl Future<Output = u8>{
	let var= 5;
    async_that_takes_u8_ref(&var) // Error
}

it says : "ERROR: var does not live long enough"

Solution

You can work around this problem by putting the argument with the call to async function into async block , await the function inside of the block as follows:

fn func_that_envokes_yet_another_async()->impl Future<Output = u8>{
	async {
    	let var= 5;
    	async_that_takes_u8_ref(&var).await
    }
        
}

This way, you essentially turn an async function that takes references into 'static future, siliencing complaints of compiler.

profile
Dude with existential crisis

0개의 댓글