I'm trying to create an async trait using the async-trait crate. I want the trait A to be implemented by B and I want B to house another of it's kind. A dyn type also implementing the A trait.
Minimal example with A also taking a generic type T because in my real example it does that for other reasons, but including it here in case it influences the solution.
#[async_trait]
trait A<T = ()> {
async fn foo(&mut self) -> u8;
}
struct B<T> {
a: Box<dyn A<T>>,
}
impl<T: Send + Unpin> A<T> for B<T> {
fn foo<'a, 'b>(& 'a mut self) -> Pin<Box<dyn Future<Output = u8> + Send + 'b>> where 'a: 'b, Self: 'b {
async fn run<T: Send + Unpin>(_self: &mut B<T>) -> u8 {
let a = _self.a.foo();
let a = a.await;
return a;
}
Box::pin(run(self)) // future returned by `run` is not `Send`
}
}
However, that would mean you cannot rely on the future returned by A::foo to be Send. This makes it impossible to move Futures to other threads. So this solution is normally not what you would want to do. But I wanted to mention it nonetheless.