简体   繁体   中英

How I can know if something is initialised in Rust?

I have some pseudocode that checks if a variable is null :

Test test;

if (test == null) {
    test = new Test();
}

return test;

How would I do something like this in Rust? This is my attempt so far:

struct Test {
    time: f64,
    test: Test,
}

impl Test {
    fn get(&self) -> Test {

        if self.test == null {
            // <--

            self.test = Test { time: 1f64 };
        } else {
            self.test
        }
    }
}

Uninitialized variables cannot be detected at runtime since the compiler won't let you get that far.

If you wish to store an optional value, however, the Option<...> type is handy for that. You can then use match or if let statements to check:

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM