Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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