Files
my-vault/04_Archive/Inbox-Clippings/2023/03/Scope and Shadowing - Rust By Example.md
T

55 lines
1.5 KiB
Markdown

---
page-title: "Scope and Shadowing - Rust By Example"
url: https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html
date: "2023-03-23 13:59:16"
---
## [Scope and Shadowing](https://doc.rust-lang.org/rust-by-example/variable_bindings/scope.html#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 `{}`.
``` rust
fn main() {
// This binding lives in the main function
let long_lived_binding = 1;
// This is a block, and has a smaller scope than the main function
{
// This binding only exists in this block
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding);
}
// End of the block
// Error! `short_lived_binding` doesn't exist in this scope
println!("outer short: {}", short_lived_binding);
// FIXME ^ Comment out this line
println!("outer long: {}", long_lived_binding);
}
```
Also, [variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) is allowed.
``` rust
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);
}
```