24

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
        }
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Angel Angel
  • 19,670
  • 29
  • 79
  • 105
  • 5
    Try creating and using an uninitialized value :) – A.B. Apr 01 '16 at 18:49
  • @A.B. You're right, I think rephrase the question with what I get, I now feel more stupid my intention is created a singleton – Angel Angel Apr 01 '16 at 19:41
  • Your `Test` struct has a field `test` that is the same type as the struct. Did you mean for this to be the case? – quornian Apr 01 '16 at 22:18
  • @quornian My intention was to create a singleton, http://stackoverflow.com/questions/36364415/how-i-can-create-a-simple-basic-singleton – Angel Angel Apr 01 '16 at 22:41

1 Answers1

38

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");
}
quornian
  • 9,495
  • 6
  • 30
  • 27
  • thanks for your answer to my original question a bit strange, I just did an update, perhaps, you can orient me? – Angel Angel Apr 01 '16 at 19:17