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