如何返回一个具有实现`Read`和`Write`特征的泛型类型的结构?

时间:2017-04-02 16:07:51

标签: rust

我正在尝试将TcpStreamTlsStream包装在一个对象中,以便我可以使用一个结构与它们中的任何一个进行交互。我试图根据配置值将io方法委托给一个或另一个,但无法弄清楚如何返回一个具有实现ReadWrite特征的泛型类型的结构

我的代码如下

pub struct TcpStream<T: Read + Write> {
    io_delegate: T,
    config: Config,
}

impl<T> TcpStream<T>
    where T: Read + Write
{
    pub fn connect<A: ToSocketAddrs>(config: Config, addr: A) -> io::Result<TcpStream<T>> {
        let tcp_stream = net::TcpStream::connect(addr).unwrap();
        if config.ssl {
            let tls_stream = TlsConnector::builder()
                .unwrap()
                .build()
                .unwrap()
                .connect("rem", tcp_stream)
                .unwrap();
            return Ok(TcpStream {
                          config: config,
                          io_delegate: tls_stream,
                      });
        }
        return Ok(TcpStream {
                      config: config,
                      io_delegate: tcp_stream,
                  });
    }
}

当我尝试编译时,我收到以下错误

error[E0308]: mismatched types
  --> src/rem/tcp_stream.rs:19:23
   |
19 |               return Ok(TcpStream {
   |  _______________________^ starting here...
20 | |                 config: config,
21 | |                 io_delegate: tls_stream
22 | |             });
   | |_____________^ ...ending here: expected type parameter, found struct `native_tls::TlsStream`
   |
   = note: expected type `rem::tcp_stream::TcpStream<T>`
              found type `rem::tcp_stream::TcpStream<native_tls::TlsStream<std::net::TcpStream>>`

error[E0308]: mismatched types
  --> src/rem/tcp_stream.rs:24:19
   |
24 |           return Ok(TcpStream{
   |  ___________________^ starting here...
25 | |                 config: config,
26 | |                 io_delegate: tcp_stream
27 | |         });
   | |_________^ ...ending here: expected type parameter, found struct `std::net::TcpStream`
   |
   = note: expected type `rem::tcp_stream::TcpStream<T>`
              found type `rem::tcp_stream::TcpStream<std::net::TcpStream>`

有没有办法实现这类事情?

1 个答案:

答案 0 :(得分:1)

我不确定这是否是最佳解决方案,但似乎确实有效。

我创建了一个新特性,它是Read + Write的组合,然后将其存储为我的struct中的Box

trait ReadWrite : Read + Write {}

impl<T: Read + Write> ReadWrite for T {}

pub struct TcpStream{
    io_delegate : Box<ReadWrite>,
    config: Config
}

impl TcpStream {

    pub fn connect<A: ToSocketAddrs>(config: Config, addr: A) -> TcpStream {
        let tcp_stream = net::TcpStream::connect(addr).unwrap();
        if config.ssl {
            let tls_stream = TlsConnector::builder().unwrap().build().unwrap().connect("rem", tcp_stream).unwrap();
            return TcpStream {
                config: config,
                io_delegate: Box::new(tls_stream)
            };
        }
        return TcpStream{
                config: config,
                io_delegate:Box::new(tcp_stream)
        };
    }
}