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 is allowed.
1. fn main() {
2. // This binding lives in the main function
3. let long_lived_binding = 1;
5. // This is a block, and has a smaller scope than the main function
6. {
7. // This binding only exists in this block
8. let short_lived_binding = 2;
10. println!("inner short: {}", short_lived_binding);
12. // This binding *shadows* the outer one
13. let long_lived_binding = 5_f32;
15. println!("inner long: {}", long_lived_binding);
16. }
17. // End of the block
19. // Error! `short_lived_binding` doesn't exist in this scope
20. println!("outer short: {}", short_lived_binding);
21. // FIXME ^ Comment out this line
23. println!("outer long: {}", long_lived_binding);
25. // This binding also *shadows* the previous binding
26. let long_lived_binding = 'a';
28. println!("outer long: {}", long_lived_binding);
29. }
