使用特定结构作为参数的特征实现

时间:2017-02-01 13:22:55

标签: types rust traits

我有可读写流的特性(如success: function (data) { // Insert your html code into the page using ".html(html)" method // or other similar method. } ):

TcpStream

我想用pub trait MyTraitPool<T: Read + Write> { fn acquire(&self, &String) -> T; fn free(&self, T); } 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); } } 方法中收到错误“expected type parameter,found std::net::TcpStream”。至于acquire方法,我知道freeshutdown - 具体,但我想在此时针对TcpStream特定实施,因此能够调用TcpStream - 具体方法。那我该怎么做呢?

作为旁注:实现只是我想做什么样的事情的一个例子,而不是代码如何运作的例子!

1 个答案:

答案 0 :(得分:1)

不是让MyPool特征变得通用,而是让你的MyStream通用,并创建一个中间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() } } 特征,为你提供所需的所有方法:

Maybe

实际上不需要关闭的流只会将实现留空。