diff --git a/src/variable_bindings/scope.md b/src/variable_bindings/scope.md index d9639b42e3..9e3c79e3ee 100644 --- a/src/variable_bindings/scope.md +++ b/src/variable_bindings/scope.md @@ -1,9 +1,7 @@ # Scope and Shadowing Variable bindings have a scope, and are constrained to live in a *block*. A -block is a collection of statements enclosed by braces `{}`. Also, [variable -shadowing][variable-shadow] is allowed. - +block is a collection of statements enclosed by braces `{}`. ```rust,editable,ignore,mdbook-runnable fn main() { // This binding lives in the main function @@ -15,11 +13,6 @@ fn main() { let short_lived_binding = 2; println!("inner short: {}", short_lived_binding); - - // This binding *shadows* the outer one - let long_lived_binding = 5_f32; - - println!("inner long: {}", long_lived_binding); } // End of the block @@ -28,12 +21,26 @@ fn main() { // FIXME ^ Comment out this line println!("outer long: {}", long_lived_binding); - - // This binding also *shadows* the previous binding - let long_lived_binding = 'a'; - - println!("outer long: {}", long_lived_binding); } ``` +Also, [variable shadowing][variable-shadow] is allowed. +```rust,editable,ignore,mdbook-runnable +fn main() { + let shadowed_binding = 1; + { + println!("before being shadowed: {}", shadowed_binding); + + // This binding *shadows* the outer one + let shadowed_binding = "abc"; + + println!("shadowed in inner block: {}", shadowed_binding); + } + println!("outside inner block: {}", shadowed_binding); + + // This binding *shadows* the previous binding + let shadowed_binding = 2; + println!("shadowed in outer block: {}", shadowed_binding); +} +``` [variable-shadow]: https://en.wikipedia.org/wiki/Variable_shadowing