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,26 @@ 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, [ variable shadowing] [ variable-shadow ] is allowed.
27+ ``` rust,editable,ignore,mdbook-runnable
28+ fn main() {
29+ let shadowed_binding = 1;
3830
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+ ```
3946[ variable-shadow ] : https://en.wikipedia.org/wiki/Variable_shadowing
0 commit comments