特质的类型成员需要发送

问题描述

我有两个特征:ProcessorPersist。第一个负责处理某些实体,第二个负责 异步 持久化处理后的实体。

鉴于我要实现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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...