I have a trait that has both non-async function and async function like this:
trait TestTrait {
fn some_func(&self);
async fn some_async_func(&self);
}
struct TestStruct {}
impl TestTrait for TestStruct {
fn some_func(&self) {}
async fn some_async_func(&self) {}
}
fn main() {
let x: Box<dyn TestTrait> = Box::new(TestStruct {});
println!("Hello, world!");
}
The compiler reject to compile the code, and what's the correct way to define such trait and Box?
async
method in trait introduces an unnamable associated type, as it is desugared into something like this:
trait TestTrait {
type some_async_func_ReturnType: Future<Output = ()>;
fn some_func(&self);
fn some_async_func(&self) -> Self::some_async_func_ReturnType;
}
To use a dyn Trait
you need to define all its associated types (e.g. Box<dyn Foo<Goo = u32>>
), but here you cannot because the associated type is unnamable.
To work around that you can use a dynamic Box
ed future:
trait TestTrait {
fn some_func(&self);
fn some_async_func(&self) -> Box<dyn Future<Output = ()>>;
}
I found a crate async-trait
which fits my situation.
I think I can use the crate to automatically rewrite the async functions for me.