How can i await inside a trait

hello everyone, i am currently stuck inside a trait, trying to call an async code, is there a way to await for code inside a trait? without using any crates other than futures or tokio?

You need to make an ordinary function returning Pin<Box<dyn Future>>

trait MyTrait {
    fn do_async<'a>(&'a self) -> Pin<Box<dyn Future<Output = String> + 'a>> {
        Box::pin(async move {
            ...
        })
    }
}

The lifetime says that the boxed future borrows from self.

This is what the async-trait crate does behind the scenes.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.