-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added blocks and scopes section (#1822)
- Loading branch information
1 parent
b5b06b5
commit fccdc0d
Showing
3 changed files
with
36 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# Scopes and Shadowing | ||
|
||
A variable's scope is limited to the enclosing block. | ||
|
||
You can shadow variables, both those from outer scopes and variables from the | ||
same scope: | ||
|
||
```rust,editable | ||
fn main() { | ||
let a = 10; | ||
println!("before: {a}"); | ||
{ | ||
let a = "hello"; | ||
println!("inner scope: {a}"); | ||
let a = true; | ||
println!("shadowed in inner scope: {a}"); | ||
} | ||
println!("after: {a}"); | ||
} | ||
``` | ||
|
||
<details> | ||
|
||
- Show that a variable's scope is limited by adding a `b` in the inner block in | ||
the last example, and then trying to access it outside that block. | ||
- Shadowing is different from mutation, because after shadowing both variable's | ||
memory locations exist at the same time. Both are available under the same | ||
name, depending where you use it in the code. | ||
- A shadowing variable can have a different type. | ||
- Shadowing looks obscure at first, but is convenient for holding on to values | ||
after `.unwrap()`. | ||
|
||
</details> |