AsyncWrite我有一个实现和 的自定义套接字AsyncRead。我想将 dyn 存储到该套接字,但我想同时使用两者AsyncWrite/Read,如下所示:
#[derive(Clone)]
pub struct AsyncTransporter {
stream: Arc<dyn AsyncRead + AsyncWrite>,
}
Run Code Online (Sandbox Code Playgroud)
但这不受支持。
60 | stream: Arc<dyn AsyncRead + AsyncWrite>,
| --------- ^^^^^^^^^^ additional non-auto trait
| |
| first non-auto trait
|
= help: consider creating a new trait with all of these as super-traits and using that trait here instead: `trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {}`
Run Code Online (Sandbox Code Playgroud)
如果我这样做trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {},这两个特征的方法将如何实现?
如果我这样做
trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {},这两个特征的方法将如何实现?
trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {}需要 的实现者NewTrait首先实现AsyncReadand AsyncWrite,因此如果您有一个实现了 的类型NewTrait,则可以依靠AsyncReadandAsyncWrite的方法就在那里。因此,这并不是“如何实现这两个特征的方法”的问题,而是“对于实现和且一无所知的NewTrait任意类型将如何实现?”的问题。AsyncReadAsyncWriteNewTrait
响应是,通过为实现这两者的所有类型提供一揽子实现:NewTrait
impl<T> NewTrait for T
where
T: AsyncRead + AsyncWrite
{
}
Run Code Online (Sandbox Code Playgroud)
通过该实现,任何既实现AsyncRead又AsyncWrite实现NewTrait.