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.