Partially Initialized Structure

When creating a structure in Rust, it seems that it is impossible to create it without setting all the fields. So for example with the following code

struct Connection { url: String, stream: TcpStream } 

You cannot set the URL without specifying TcpStream .

 // Throws exception asking for 'stream' let m = Connection { url:"www.google.com".to_string() }; 

So, how can you create these links, which may be Option<None> until a later time?

The best I have found is to use the Default attribute. But I’d better not create a TcpStream until later than when initializing the structure. Can I do this with something like Box ?

+6
source share
2 answers

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 { // can use the stream here } else { println!("the stream hasn't been initialized yet"); } } } 

This is similar to what is done in Swift if you are familiar with this language.

+6
source

All fields really need to be initialized when creating a struct instance (no zero in rust), so all memory is allocated. Often, a dedicated method is used (for example, new ), which sets default values ​​for fields that must be changed at a later stage.

I would use Box when you don't know the size of the field (e.g. Vec ).

+3
source

Source: https://habr.com/ru/post/987716/


All Articles