可以使用async_trait的时候,方法参数类型是静态的,因此与动态分派可能会有一些限制。但是你可以使用Box
下面是代码示例:
use async_trait::async_trait;
trait SomeTrait {
async fn do_something(&self);
}
struct A;
#[async_trait]
impl SomeTrait for A {
async fn do_something(&self) {
println!("A is doing something");
}
}
struct B;
#[async_trait]
impl SomeTrait for B {
async fn do_something(&self) {
println!("B is doing something");
}
}
#[async_trait]
trait SomeOtherTrait {
async fn call_do_something(&self, thing: &dyn SomeTrait);
}
struct C;
#[async_trait]
impl SomeOtherTrait for C {
async fn call_do_something(&self, thing: &dyn SomeTrait) {
thing.do_something().await;
}
}
#[tokio::main]
async fn main() {
let a = A {};
let b = B {};
let c = C {};
c.call_do_something(&a).await;
c.call_do_something(&b).await;
}