0Pricing
Learn Rust Coding · Lesson

Shadowing

Rebinding variables.

What Is Shadowing?

Shadowing means declaring a new variable with the same name as a previous one. The new binding 'shadows' the old.

You do this by repeating let with the same name.

fn main() {
    let x = 5;
    let x = x + 1;
    let x = x * 2;
    println!("x is {}", x);
}

Shadowing Is Not Mutation

Shadowing creates a brand-new variable. This differs from mut, which reuses the same variable.

Because each let is a new binding, the values can even have different types.

fn main() {
    let y = 10;        // immutable
    let y = y + 5;     // new binding, also immutable
    println!("y is {}", y);
}

All lessons in this course

  1. let and Mutability
  2. Scalar Types
  3. Compound Types
  4. Shadowing
← Back to Learn Rust Coding