Skip to content

Commit

Permalink
Merge pull request #1370 from xiaochuanyu/split-shadowing-example
Browse files Browse the repository at this point in the history
Split out variable shadowing into a separate example
  • Loading branch information
marioidival authored Aug 26, 2020
2 parents 789a37b + ab1ba4f commit 9477098
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions src/variable_bindings/scope.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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

0 comments on commit 9477098

Please sign in to comment.