简体   繁体   English

以特定结构作为参数的特性实现

[英]Trait implementation with specific struct as parameter

I have a trait for readable and writable streams (like TcpStream ):我有可读和可写流的特征(如TcpStream ):

pub trait MyTraitPool<T: Read + Write> {
    fn acquire(&self, &String) -> T;
    fn free(&self, T);
}

I want to implement that trait with TcpStream as T , so I would like to write我想用TcpStream作为T实现那个特征,所以我想写

struct MyPool;

impl<T> MyTraitPool<T> for MyPool
    where T: Read + Write {

    fn acquire(&self, addr: &String) -> T {
        TcpStream::connect(addr.as_str()).unwrap()
    }

    fn free(&self, con: T) {
        con.shutdown(Shutdown::Both);
    }
}

I get the error "expected type parameter, found struct std::net::TcpStream " in the acquire method.我在acquire方法中收到错误“预期类型参数,找到 struct std::net::TcpStream ”。 As for the free method, I know that shutdown is TcpStream -specific, but I would like to have an implementation specific for TcpStream s at that point and hence be able to call TcpStream -specific methods.对于free的方法,我知道, shutdownTcpStream特异性,但我想有一个实现特定的TcpStream在该点s,因此能够调用TcpStream特异性方法。 So how do I go about doing so?那么我该怎么做呢?

As a side note: the implementation is just an example for what kind of things I would like to do, not for how the code operates later!作为旁注:实现只是我想做什么样的事情的一个例子,而不是代码以后如何运行!

Instead of making the MyTraitPool trait generic, you'd make your MyPool generic and you'd create an intermediate MyStream trait to offer you all methods you need:不是让MyTraitPool trait 泛型,而是让MyPool泛型,然后创建一个中间MyStream trait 来提供你需要的所有方法:

trait MyStream: Read + Write {
    fn connect(&str) -> Self;
    fn shutdown(self);
}
impl MyStream for TcpStream {
    fn connect(addr: &str) -> Self { TcpStream::connect(addr) }
    fn shutdown(self) { TcpStream::shutdown(self, Shutdown::Both); }
}
impl<T: MyStream> MyTraitPool for MyPool<T> {
    fn acquire(&self, addr: &str) -> T {
        MyStream::connect(addr)
    }
    fn free(&self, con: T) {
        con.shutdown()
    }
}

Streams which do not actually need to shutdown, would simply leave the implementation empty.实际上不需要关闭的流只会将实现留空。

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

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