如何创建具有多个特征范围的特征对象?

时间:2018-06-21 15:00:25

标签: rust polymorphism traits

我有一个返回一些对象的函数。该函数的调用者不必关心实际的类型,而应关心该类型实现的特征:

trait CanWalk {
    fn walk(&self) {}
}

trait CanFly {
    fn fly(&self) {}
}

struct Woodpecker {}

impl CanWalk for Woodpecker {}
impl CanFly for Woodpecker {}

fn make_woodpecker() -> CanWalk + CanFly {
    Woodpecker {}
}

fn main() {}

编译器抱怨:

error[E0225]: only auto traits can be used as additional traits in a trait object
  --> src/main.rs:14:35
   |
14 | fn make_woodpecker() -> CanWalk + CanFly {
   |                                   ^^^^^^ non-auto additional trait

那是为什么?我该怎么办?

在我的实际项目中,我有一些对流(或基本上支持Read + Write的东西)进行I / O的函数。因此,签名如下所示:

fn do_some_io<T: Read + Write>(io_thing: T)

通常,这将是一个native_tls::TlsStream,但如果用户这样说(在运行时),我也希望能够传递一个std::net::TcpStream。遵循以下原则:

fn connect_tcp(host: &str, ...) -> Result<Read + Write> {...}
fn connect_tls(host: &str, ...) -> Result<Read + Write> {...}

fn connect(insecure: bool, host: &str, ...) -> Result<Read + Write> {
    if insecure {
        connect_tcp(...)
    } else {
        connect_tls(...)
    }
}

如果具有两个边界的特征对象不起作用(还?),如何在Rust中实现此功能?

0 个答案:

没有答案