]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/variable_bindings/scope.md
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / src / doc / rust-by-example / src / variable_bindings / scope.md
1 # Scope and Shadowing
2
3 Variable bindings have a scope, and are constrained to live in a *block*. A
4 block is a collection of statements enclosed by braces `{}`.
5 ```rust,editable,ignore,mdbook-runnable
6 fn main() {
7 // This binding lives in the main function
8 let long_lived_binding = 1;
9
10 // This is a block, and has a smaller scope than the main function
11 {
12 // This binding only exists in this block
13 let short_lived_binding = 2;
14
15 println!("inner short: {}", short_lived_binding);
16 }
17 // End of the block
18
19 // Error! `short_lived_binding` doesn't exist in this scope
20 println!("outer short: {}", short_lived_binding);
21 // FIXME ^ Comment out this line
22
23 println!("outer long: {}", long_lived_binding);
24 }
25 ```
26 Also, [variable shadowing][variable-shadow] is allowed.
27 ```rust,editable,ignore,mdbook-runnable
28 fn main() {
29 let shadowed_binding = 1;
30
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 ```
46 [variable-shadow]: https://en.wikipedia.org/wiki/Variable_shadowing