如何解决特质的类型成员需要发送
我有两个特征: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 举报,一经查实,本站将立刻删除。