Closed5

async_traitを使っていたら「future created by async block is not `Send`」みたいなエラーになる

kgmyshinkgmyshin

こういうコードは起きない

#[async_trait]
pub trait Boo {
  async fn booboo(&self) -> String;
}

struct BooClient<'a, T: Boo> {
  boo: &'a T,
}

impl<'a, T: Boo> BooClient<'a, T> {
  async fn execute(&self) -> String {
    self.boo.booboo().await
  }
}
kgmyshinkgmyshin

こういうコードは起きる

#[async_trait]
pub trait Boo {
  async fn booboo(&self) -> String;
}

#[async_trait]
trait AsyncBooClient {
  async fn hello(&self) -> String;
}

struct AsyncBookClientImpl<'a, T: Boo> {
  boo: &'a T,
}

#[async_trait]
impl<'a, T: Boo> AsyncBooClient for AsyncBookClientImpl<'a, T> {
  async fn hello(&self) -> String {
    self.boo.booboo().await
  }
}

kgmyshinkgmyshin

要は async_trait な トレイト をメンバーにもつ struct が、別の async_trait な トレイト を impl する際に発生する。

kgmyshinkgmyshin

対応としては、これで良さそう。

#[async_trait]
impl<'a, T: Boo + Send + Sync> AsyncBooClient for AsyncBookClientImpl<'a, T> {
  async fn hello(&self) -> String {
    self.boo.booboo().await
  }
}
このスクラップは2022/03/06にクローズされました