Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can know if something is initialised in Rust?

Tags:

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
        }
    }
}
like image 480
Angel Angel Avatar asked Apr 01 '16 18:04

Angel Angel


People also ask

How do you check NOT NULL in Rust?

Rust does not support NULL; therefore, we don't perform NULL checks on values. It does not even have keywords for NULL. However, it provides an enum Option that we can use similarly to Java 8 Optional.

How do you initialize a variable in Rust?

A variable is initialized with the let keyword, whereas a constant is initialized with the const keyword.


1 Answers

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");
}
like image 125
quornian Avatar answered Oct 07 '22 01:10

quornian