dtolnay / async-trait

Type erasure for async trait methods
Apache License 2.0
1.81k stars 84 forks source link

Problem with trait method default implemetation #140

Closed andreytkachenko closed 3 years ago

andreytkachenko commented 3 years ago

Here is the example trait:

#[async_trait]
trait Test {
    async fn test1(&mut self);
    async fn test2(&mut self) {}
}

and this usage compiles:

fn test<T: Test + 'static>(mut t: T) {
    tokio::task::spawn_local(async move {
        t.test1().await;
    });
}

but this one doesn't

fn test<T: Test + 'static>(mut t: T) {
    tokio::task::spawn_local(async move {
        t.test2().await;
    });
}

here the compiler error:

error[E0277]: `T` cannot be sent between threads safely
  --> src/main.rs:11:11
   |
11 |         t.test2().await;
   |           ^^^^^ `T` cannot be sent between threads safely
   |
help: consider further restricting this bound
   |
9  | fn test<T: Test + 'static + Send>(mut t: T) {
   |                           ^^^^^^
andreytkachenko commented 3 years ago

Found the answer. Solution is:

#[async_trait(?Send)]
trait Test {
    async fn test1(&mut self);
    async fn test2(&mut self) {}
}