1 % Checked Uninitialized Memory
3 Like C, all stack variables in Rust are uninitialized until a value is
4 explicitly assigned to them. Unlike C, Rust statically prevents you from ever
5 reading them until you do:
15 src/main.rs:3:20: 3:21 error: use of possibly uninitialized variable: `x`
16 src/main.rs:3 println!("{}", x);
20 This is based off of a basic branch analysis: every branch must assign a value
21 to `x` before it is first used. Interestingly, Rust doesn't require the variable
22 to be mutable to perform a delayed initialization if every branch assigns
23 exactly once. However the analysis does not take advantage of constant analysis
24 or anything like that. So this compiles:
53 src/main.rs:6:17: 6:18 error: use of possibly uninitialized variable: `x`
54 src/main.rs:6 println!("{}", x);
66 // Don't care that there are branches where it's not initialized
67 // since we don't use the value in those branches
71 Of course, while the analysis doesn't consider actual values, it does
72 have a relatively sophisticated understanding of dependencies and control
73 flow. For instance, this works:
79 // Rust doesn't understand that this branch will be taken unconditionally,
80 // because it relies on actual values.
82 // But it does understand that it will only be taken once because
83 // we unconditionally break out of it. Therefore `x` doesn't
84 // need to be marked as mutable.
89 // It also knows that it's impossible to get here without reaching the break.
90 // And therefore that `x` must be initialized here!
94 If a value is moved out of a variable, that variable becomes logically
95 uninitialized if the type of the value isn't Copy. That is:
101 let z1 = x; // x is still valid because i32 is Copy
102 let z2 = y; // y is now logically uninitialized because Box isn't Copy
106 However reassigning `y` in this example *would* require `y` to be marked as
107 mutable, as a Safe Rust program could observe that the value of `y` changed:
111 let mut y = Box::new(0);
112 let z = y; // y is now logically uninitialized because Box isn't Copy
113 y = Box::new(1); // reinitialize y
117 Otherwise it's like `y` is a brand new variable.