extern crate rand;
fn main() {
let a: bool;
let b: bool;
let (dx, dy) = (rand::random::<i32>(), rand::random::<i32>());
if dx < 0 && dy < 0 {
a = true;
b = true;
} else if dx < 0 && dy >= 0 {
a = true;
b = false;
} else if dx >= 0 && dy < 0 {
a = false;
b = true
} else if dx >= 0 && dy >= 0 {
a = false;
b = false;
}
let test = (a, b);
println!("{:?}", test);
}
I get use of possibly uninitialized variable errors for a and b, but I'm having trouble seeing a case in which those could remain uninitialized. What am I missing?
The compiler doesn't look at all the conditions and see that there is no possible other condition that could happen. You've covered all possibilities, but, the compiler isn't "smart" enough to know that. All it knows it that you have a series of "if" branches all of which could in theory evaluate to false in which case you would never set a and b with values. When you have exhaustive conditions like this, always make the last one an "else" instead of an "if". In other words, once you've eliminated everything else you care about, whatever is left should just be handled with "else", then, the compiler knows that no matter what a and b will be set.
You could potentially express the same logic as an exhaustive match on a value of type (bool, bool), in which case any value initialized in all four branches would be considered initialized after the match-expression.