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:
16 3 | println!("{}", x);
17 | ^ use of possibly uninitialized `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:
54 6 | println!("{}", x);
55 | ^ use of possibly uninitialized `x`
67 // Don't care that there are branches where it's not initialized
68 // since we don't use the value in those branches
72 Of course, while the analysis doesn't consider actual values, it does
73 have a relatively sophisticated understanding of dependencies and control
74 flow. For instance, this works:
80 // Rust doesn't understand that this branch will be taken unconditionally,
81 // because it relies on actual values.
83 // But it does understand that it will only be taken once because
84 // we unconditionally break out of it. Therefore `x` doesn't
85 // need to be marked as mutable.
90 // It also knows that it's impossible to get here without reaching the break.
91 // And therefore that `x` must be initialized here!
95 If a value is moved out of a variable, that variable becomes logically
96 uninitialized if the type of the value isn't Copy. That is:
102 let z1 = x; // x is still valid because i32 is Copy
103 let z2 = y; // y is now logically uninitialized because Box isn't Copy
107 However reassigning `y` in this example *would* require `y` to be marked as
108 mutable, as a Safe Rust program could observe that the value of `y` changed:
112 let mut y = Box::new(0);
113 let z = y; // y is now logically uninitialized because Box isn't Copy
114 y = Box::new(1); // reinitialize y
118 Otherwise it's like `y` is a brand new variable.