11# Scope and Shadowing
22
33Variable 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 ` {} ` .
75``` rust,editable,ignore,mdbook-runnable
86fn main() {
97 // This binding lives in the main function
@@ -15,11 +13,6 @@ fn main() {
1513 let short_lived_binding = 2;
1614
1715 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);
2316 }
2417 // End of the block
2518
@@ -28,12 +21,23 @@ fn main() {
2821 // FIXME ^ Comment out this line
2922
3023 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);
3624}
3725```
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;
3831
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+ ```
3943[ variable-shadow ] : https://en.wikipedia.org/wiki/Variable_shadowing
0 commit comments