Scopes and Shadowing

You can shadow variables, both those from outer scopes and variables from the same scope:

  1. fn main() {
  2. let a = 10;
  3. println!("before: {a}");
  4. {
  5. let a = "hello";
  6. println!("inner scope: {a}");
  7. let a = true;
  8. println!("shadowed in inner scope: {a}");
  9. }
  10. println!("after: {a}");
  11. }
  • Definition: 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().
  • The following code demonstrates why the compiler can’t simply reuse memory locations when shadowing an immutable variable in a scope, even if the type does not change.
  1. fn main() {
  2. let a = 1;
  3. let b = &a;
  4. let a = a + 1;
  5. println!("{a} {b}");
  6. }