我有一些伪代码来检查变量是否为
null
:
Test test;
if (test == null) {
test = new Test();
}
return test;
我该如何在 Rust 中做这样的事情?这是我迄今为止的尝试:
struct Test {
time: f64,
test: Test,
}
impl Test {
fn get(&self) -> Test {
if self.test == null { // <--
self.test = Test { time: 1f64 };
} else {
self.test
}
}
}
未初始化的变量无法在运行时检测到,因为编译器不会让你做到这一点。
Option<...>
类型非常方便。然后您可以使用 match
或 if let
语句来检查:
let mut x: Option<f32> = None;
// ...
x = Some(3.5);
// ...
if let Some(value) = x {
println!("x has value: {}", value);
}
else {
println!("x is not set");
}