简体   繁体   English

实施可选特征要求

[英]Implementing optional trait requirement

I am trying to find a way to group different traits so that the generic variable can hold these traits.我正在尝试找到一种方法来对不同的特征进行分组,以便通用变量可以保存这些特征。

For example, I am trying to have T such it's with the traits io::Read + io::Write + io::Seek.例如,我试图让 T 具有特征 io::Read + io::Write + io::Seek。 Now, that can be easily done in rust using the following code:现在,可以使用以下代码在 rust 中轻松完成:

pub trait RWS:  io::Read + io::Write + io::Seek{}
impl<T> RWS for T where T: io::Read + io::Write  + io::Seek{}

However, the problem comes when trying to have a function that takes in BufReader, because BufReader doesn't implement io::Write.但是,当尝试使用接收 BufReader 的 function 时出现问题,因为 BufReader 没有实现 io::Write。

Therefore, is there a possibility to implement something that looks like the following for a general type that can be either one?因此,是否有可能为可以是任何一种的通用类型实现如下所示的东西?

pub trait RWS:  io::Read || io::Write || io::Seek{}
impl<T> RWS for T where T: io::Read || io::Write  || io::Seek{}

If you just need a field that can store anything implementing one of these three traits at a time, I would suggest using a simple enum:如果您只需要一个可以一次存储实现这三个特征之一的任何内容的字段,我建议使用一个简单的枚举:

enum RWS<'a> { // The lifetime parameter can be omitted if you will only be storing fields of `'static` type.
    Read(Box<dyn Read + 'a>),
    Write(Box<dyn Write + 'a>),
    Seek(Box<dyn Seek + 'a>),
}

You could add from_read , from_write , from_seek constructors to this enum for convenience, and match on it in your struct's methods.为方便起见,您可以将from_readfrom_writefrom_seek构造函数添加到此枚举中,并在结构的方法中对其进行匹配。

However, there are some limitations to this approach.但是,这种方法有一些限制。 Since it takes ownership of the value and erases its concrete type, you cannot do something like the following:由于它拥有值的所有权并删除其具体类型,因此您不能执行以下操作:

let bufreader: std::io::BufReader = /* ... */;
self.rws = RWS::Read(Box::new(bufreader));
// later...
if let self.rws = RWS::Read(val) {
    self.rws = RWS::Seek(val); // compile error, even though `BufReader` impls `Seek`
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM