Hello,
I'm currently working on a project where I'm using the async_trait
crate to define async functions in traits. Here's a simplified version of my code:
use std::marker::PhantomData;
use async_trait::async_trait;
pub trait RT {
fn return_type() -> String;
}
#[derive(Default)]
pub struct FunctionCall<R> {
pub(crate) datatype: PhantomData<R>,
}
impl<R: RT> FunctionCall<R> {
pub async fn call(&self) -> Result<R, String>{
todo!()
}
}
struct Wrapper {
a: String
}
impl Wrapper {
pub fn method<R: RT>() -> FunctionCall<R> {
todo!()
}
}
pub struct A {}
#[async_trait]
pub trait test_call{
async fn try_call<R: RT + Send >(&self) -> Result<R, String>;
}
#[async_trait]
impl test_call for A {
async fn try_call<R: RT + Send>(&self) -> Result<R, String>{
Wrapper::method::<R>().call().await
}
}
I'm getting an error that: future cannot be sent between threads safely
Interestingly, when I change the trait definition to R: RT + Send + Sync
, the error goes away.
I would appreciate any help or guidance on why Sync
is needed in this case and how the Send
and Sync
traits interact in the context of async functions and traits. Thanks in advance.