I was hit with the possibly-uninitialized variable error, although I'm convinced that this should never be the case.
(The rustc --version is rustc 1.51.0 (2fd73fabe 2021-03-23))
fn example(discriminant: bool) {
let value;
if discriminant {
value = 0;
}
// more code [...]
if discriminant {
println!("{}", value);
}
}
Here's the error message:
error[E0381]: borrow of possibly-uninitialized variable: `value`
--> src/raytracing/intersect.rs:8:24
|
10 | println!("{}", value);
| ^^^^^ use of possibly-uninitialized `value`
Reasoning
I did expect the example to compile (even though seperating the if-blocks as shown isn't "good style" IMHO):
- As
discriminantis immutable, I expect the secondifblock to never execute without the first. - Therefore, the variable should always be defined at the time of borrow in
println!().
Possible mitigation
The error can be 'silenced' by initializing value with a temporary value.
I strongly disagree with this approach because
- a temporary value could be wrong in a mathematical sense due to it being impossible to compute in other code paths.
- Also, this could hide the fact that the value isn't properly defined during development, limiting the compiler's abilities to signal errors.
Question
Can someone clarify if this case is intended behaviour or maybe a compiler bug?