问题描述
我有两个特征:Processor
和Persist
。第一个负责处理某些实体,第二个负责 异步 持久化处理后的实体。
鉴于我要实现trait ProcessPersist
的两个特征,同时兼顾了处理和持久性。外观如下, 编译良好 strong>
use async_trait::*;
trait Processor<T>{
type Output: Send; // <----------------------- Note Send here
fn process(&self,t: T) -> Self::Output;
}
#[async_trait]
trait Persist<T>{
async fn persist(&self,t: T) -> Result<(),()>;
}
#[async_trait]
trait ProcessPersist<T>{
async fn process_persist(&self,()>;
}
#[async_trait]
impl<T,M> ProcessPersist<T> for M
where
T: Send + 'static,M: Processor<T> + Send + Sync,M: Persist<<M as Processor<T>>::Output>
{
async fn process_persist(&self,()> {
let out = self.process(t);
self.persist(out).await
}
}
问题:我要避免的事情是删除上下文绑定的type Output: Send
,因为这似乎限制太多了。相反,我希望以某种方式在trait ProcessPersist
实现中指定它。
有可能吗?
仅从类型Send
中删除Output
无法编译 :
use async_trait::*;
trait Processor<T>{
type Output; // <----------------------- Send is removed
fn process(&self,()> {
let out = self.process(t);
self.persist(out).await
}
}
错误消息:
error: future cannot be sent between threads safely
--> src/main.rs:47:61
|
47 | async fn process_persist(&self,()> {
| _____________________________________________________________^
48 | | let out = self.process(t);
49 | | self.persist(out).await
50 | | }
| |_____^ future returned by `__process_persist` is not `Send`
|
= help: within `impl core::future::future::Future`,the trait `std::marker::Send` is not implemented for `<M as Processor<T>>::Output`
note: future is not `Send` as this value is used across an await
--> src/main.rs:49:9
|
48 | let out = self.process(t);
| --- has type `<M as Processor<T>>::Output` which is not `Send`
49 | self.persist(out).await
| ^^^^^^^^^^^^^^^^^^^^^^^ await occurs here,with `out` maybe used later
50 | }
| - `out` is later dropped here
= note: required for the cast to the object type `dyn core::future::future::Future<Output = std::result::Result<(),()>> + std::marker::Send`
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)