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,23 @@ 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, a binding may have the same name as a binding from an outer block. This is
27
+ known as [ variable shadowing] [ variable-shadow ] .
28
+ ``` rust,editable,ignore,mdbook-runnable
29
+ fn main() {
30
+ let shadowed_binding = 1;
38
31
32
+ {
33
+ println!("before being shadowed: {}", shadowed_binding);
34
+
35
+ // This binding *shadows* the outer one
36
+ let shadowed_binding = "a";
37
+
38
+ println!("after being shadowed: {}", shadowed_binding);
39
+ }
40
+
41
+ }
42
+ ```
39
43
[ variable-shadow ] : https://en.wikipedia.org/wiki/Variable_shadowing
0 commit comments