Quantcast
Channel: User Victor Ronin - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Lifetime of a reference passed to async callback

$
0
0

I have async function to which I am passing async callback. The callback takes a reference as a parameter.

use core::future::Future;async fn foo(bar: &u32) {}async fn baz<F, Fut>(f: F)where    F: FnOnce(&u32) -> Fut,    Fut: Future<Output = ()>,{    let test: u32 = 42;    f(&test).await;}#[tokio::main]async fn main() {    baz(foo).await;}

I am getting the following error if I try to build this (playground):

error[E0308]: mismatched types  --> src/main.rs:16:5   |16 |     baz(foo).await;   |     ^^^ lifetime mismatch   |   = note: expected associated type `<for<'_> fn(&u32) -> impl Future<Output = ()> {foo} as FnOnce<(&u32,)>>::Output`              found associated type `<for<'_> fn(&u32) -> impl Future<Output = ()> {foo} as FnOnce<(&u32,)>>::Output`   = note: the required lifetime does not necessarily outlive the empty lifetimenote: the lifetime requirement is introduced here  --> src/main.rs:7:24   |7  |     F: FnOnce(&u32) -> Fut,   |                        ^^^

I understand that it's not happy about the lifetime of the reference. However, I don't understand why.

  • We borrow "test"
  • We execute callback f (which is "foo")
  • There is no way for baz exits before f is done

So, it looks like there is no way for the borrow to outlive the place where test is declared.

What am I missing?


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>