@@ -7,15 +7,17 @@ variable.
7
7
A _ local variable_ (or * stack-local* allocation) holds a value directly,
8
8
allocated within the stack's memory. The value is a part of the stack frame.
9
9
10
- Local variables are immutable unless declared otherwise. For example: ` let mut x = ... ` .
10
+ Local variables are immutable unless declared otherwise. For example:
11
+ ` let mut x = ... ` .
11
12
12
13
Function parameters are immutable unless declared with ` mut ` . The ` mut ` keyword
13
- applies only to the following parameter. For example: ` |mut x, y| ` and `fn f(mut x:
14
- Box<i32 >, y: Box<i32 >)` declare one mutable variable ` x` and one immutable
15
- variable ` y ` .
14
+ applies only to the following parameter. For example: ` |mut x, y| ` and
15
+ ` fn f(mut x: Box<i32>, y: Box<i32>)` declare one mutable variable ` x ` and one
16
+ immutable variable ` y ` .
16
17
17
18
Methods that take either ` self ` or ` Box<Self> ` can optionally place them in a
18
- mutable variable by prefixing them with ` mut ` (similar to regular arguments). For example:
19
+ mutable variable by prefixing them with ` mut ` (similar to regular arguments).
20
+ For example:
19
21
20
22
``` rust
21
23
trait Changer : Sized {
@@ -24,8 +26,29 @@ trait Changer: Sized {
24
26
}
25
27
```
26
28
27
- Local variables are not initialized when allocated. Instead, the entire frame worth of
28
- local variables are allocated, on frame-entry, in an uninitialized
29
+ Local variables are not initialized when allocated. Instead, the entire frame
30
+ worth of local variables are allocated, on frame-entry, in an uninitialized
29
31
state. Subsequent statements within a function may or may not initialize the
30
32
local variables. Local variables can be used only after they have been
31
- initialized; this is enforced by the compiler.
33
+ initialized through all reachable control flow paths.
34
+
35
+ In this next example, ` init_after_if ` is initialized after the [ ` if ` expression]
36
+ while ` uninit_after_if ` is not because it is not initialized in the ` else ` case.
37
+
38
+ ``` rust
39
+ # fn random_bool () -> bool { true }
40
+ fn initialization_example () {
41
+ let init_after_if : ();
42
+ let uninit_after_if : ();
43
+
44
+ if random_bool () {
45
+ init_after_if = ();
46
+ uninit_after_if = ();
47
+ } else {
48
+ init_after_if = ();
49
+ }
50
+
51
+ init_after_if ; // ok
52
+ // uninit_after_if; // err: use of possibly uninitialized `uninit_after_if`
53
+ }
54
+ ```
0 commit comments