An asynchronous error, I don't understand why this error occurred

use tokio;
trait MethodTrait {
    async fn async_method(&self);
}

#[derive(Clone)]
struct MyStruct {}
impl MethodTrait for MyStruct {
    async fn async_method(&self) {
        todo!() // 占位
    }
}

struct Demo<T>
where
    T: MethodTrait + Clone + Sync + Send + 'static,
{
    parser: T,
}

impl<T> Demo<T>
where
    T: MethodTrait + Clone + Sync + Send + 'static,
{
    fn new(parser: T) -> Self {
        Demo { parser }
    }
    async fn execute(&self) {
        let parser = self.parser.clone();
        tokio::spawn(async move {
            // parser.async_method().await; // 这里会报错
            test_fn().await; // 这里正常执行
        });
    }
}

#[tokio::main]
async fn main() {
    let my_struct = MyStruct {};
    let demo = Demo::new(my_struct);
    demo.execute().await;
}

async fn test_fn() {
    println!("hello world")
}

ERROR: the trait Send is not implemented for impl Future<Output = ()>, which is required by : Send

I don't understand why I can't directly write an asynchronous method here. I need to write a synchronous method and manually constrain the send return value myself.

Spawning a task with tokio::spawn requires that the inner futurue implements Send.

Rust is telling you that the trait MethodTrait requires that the desugared async fn async_method(&self) returns something that meets the bounds Future<Output = ()>, but to spawn a future, you need it to meet the bounds Future<Output = ()> + Send.

It also tells you in the error message how you can fix it; in the trait MethodTrait, you can manually desugar async fn async_method, which means that implementing async_method such that the resulting Future is not Send is a bad implementation, and thus that you can spawn it.

1 Like

See also ASYNC_FN_IN_TRAIT in rustc_lint::async_fn_in_trait - Rust

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.