Skip to content

Commit 9477098

Browse files
authored
Merge pull request #1370 from xiaochuanyu/split-shadowing-example
Split out variable shadowing into a separate example
2 parents 789a37b + ab1ba4f commit 9477098

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

src/variable_bindings/scope.md

+20-13
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
# Scope and Shadowing
22

33
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 `{}`.
75
```rust,editable,ignore,mdbook-runnable
86
fn 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

Comments
 (0)