I have an external type (protobuf:::CodedInputStream
) which expects a reference to a referenced trait-object (TcpStream
as &mut Read
).
I would like to make a type or function Connection
wrap the TcpStream
(taking ownership), together with a CodedInputStream
, in order to use it's capabilities, encapsulating the use and ownership of the TcpStream as an internal detail.
However, I can't figure out how. My naive attempt (in pseudo-rust)
struct Connection {
stream: TcpStream,
coded_stream: CodedInputStream,
}
fn new_connection(s: TcpStream) -> Connection {
Connection {
stream: s,
// Invalid, `s` has been transferred to `stream` above
coded_stream: CodedInputStream::new(&mut s),
// Invalid, `stream` is an unresolved symbol here
coded_stream: CodedInputStream::new(&mut stream),
// Omitting and mutating fails, since `coded_stream`
// must have a value and there is no "0"-value.
}
}
Am I missing something obvious? Is this generally a bad idea in Rust? Is there some other pattern for dealing with taking ownership and encapsulating a long-living object?
In Why can't I store a value and a reference to that value in the same struct? there is a similar question dealing with how to refactor internal types in order to solve the problem. Here, the CodedInputStream
is outside my control, a different solution is required (I believe).