我如何知道 Rust 中是否已初始化某些内容?

问题描述 投票:0回答:1

我有一些伪代码来检查变量是否为

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
        }
    }
}
rust
1个回答
46
投票

未初始化的变量无法在运行时检测到,因为编译器不会让你做到这一点。

但是,如果您希望存储可选值,则

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");
}
© www.soinside.com 2019 - 2024. All rights reserved.