So, one thing you can do is wrap TcpStream in Option , i.e. Option<TcpStream> . When you first build the structure, it will be None , and when you initialize it, you will make it self.stream = Some(<initialize tcp stream>) . Where you use the tcp stream, you need to check if it is Some , i.e. If it has already been initialized. If you can ensure that your behavior, you can just unwrap() , but it is probably best to do a background check anyway.
struct Connection { url: String, stream: Option<TcpStream> } impl Connection { pub fn new() -> Connection { Connection { url: "www.google.com".to_string(), stream: None, } } pub fn initialize_stream(&mut self) { self.stream = Some(TcpStream::connect("127.0.0.1:34254").unwrap()); } pub fn method_that_uses_stream(&self) { if let Some(ref mut stream) = self.stream {
This is similar to what is done in Swift if you are familiar with this language.
source share