Reputation: 942
I have a trait for readable and writable streams (like 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
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. 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. 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!
Upvotes: 2
Views: 124
Reputation: 31163
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:
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.
Upvotes: 1