在Rust中创建结构时,似乎很难在没有设置所有字段的情况下创建一个结构。例如下面的代码
struct Connection {
url: String,
stream: TcpStream
}
你是不是可以设置url
不给stream
为好。
// Compilation error asking for 'stream'
let m = Connection { url: "www.google.com".to_string() };
您如何创建这些引用,Option<None>
直到以后?
我发现最好的方法是使用Default
trait,但我宁愿不必在TcpStream
初始化该结构之后再创建。我能用类似的东西做到这一点Box
吗?
您可以做的一件事是将包裹TcpStream
在Option
,即中Option<TcpStream>
。首次构造该结构时,它将为None
,并在初始化时进行构造self.stream = Some(<initialize tcp stream>)
。无论在何处使用TCPStream
,都必须检查它是否为Some
,即是否已初始化。如果您可以保证自己的行为,那么就可以了unwrap()
,但是最好还是进行检查。
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 stream) = self.stream {
// can use the stream here
} else {
println!("the stream hasn't been initialized yet");
}
}
}
如果您熟悉该语言,则这与Swift中的操作类似。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句