1
1
# Scope and Shadowing
2
2
3
3
Variable bindings have a scope, and are constrained to live in a * block* . A
4
- block is a collection of statements enclosed by braces ` {} ` . Also, [ variable
5
- shadowing] [ variable-shadow ] is allowed.
6
-
4
+ block is a collection of statements enclosed by braces ` {} ` .
7
5
``` rust,editable,ignore,mdbook-runnable
8
6
fn main() {
9
7
// This binding lives in the main function
@@ -15,11 +13,6 @@ fn main() {
15
13
let short_lived_binding = 2;
16
14
17
15
println!("inner short: {}", short_lived_binding);
18
-
19
- // This binding *shadows* the outer one
20
- let long_lived_binding = 5_f32;
21
-
22
- println!("inner long: {}", long_lived_binding);
23
16
}
24
17
// End of the block
25
18
@@ -28,12 +21,26 @@ fn main() {
28
21
// FIXME ^ Comment out this line
29
22
30
23
println!("outer long: {}", long_lived_binding);
31
-
32
- // This binding also *shadows* the previous binding
33
- let long_lived_binding = 'a';
34
-
35
- println!("outer long: {}", long_lived_binding);
36
24
}
37
25
```
26
+ Also, [ variable shadowing] [ variable-shadow ] is allowed.
27
+ ``` rust,editable,ignore,mdbook-runnable
28
+ fn main() {
29
+ let shadowed_binding = 1;
38
30
31
+ {
32
+ println!("before being shadowed: {}", shadowed_binding);
33
+
34
+ // This binding *shadows* the outer one
35
+ let shadowed_binding = "abc";
36
+
37
+ println!("shadowed in inner block: {}", shadowed_binding);
38
+ }
39
+ println!("outside inner block: {}", shadowed_binding);
40
+
41
+ // This binding *shadows* the previous binding
42
+ let shadowed_binding = 2;
43
+ println!("shadowed in outer block: {}", shadowed_binding);
44
+ }
45
+ ```
39
46
[ variable-shadow ] : https://en.wikipedia.org/wiki/Variable_shadowing
0 commit comments