Menu
Coddy logo textTech

Shadowing Part 2

Part of the Fundamentals section of Coddy's Rust journey — lesson 48 of 75.

When you shadow a variable in Rust, the new variable is completely independent from the original one, and it needs its own mutability declaration. Shadowing does not inherit the mutability of the original variable.

let mut mut_val = 7;
// Original variable is mutable
{ 
    let mut_val = 8;
    // This is a new variable that shadows the outer mut_val
      
    mut_val = 50;
    // An error occurred because
    // mut_val is not mutable
}
// Here it is okay 
// mut_val is not frozen in this scope
mut_val = 3;

To fix it we can add mut in the inner scope:

{
	let mut mut_val = 8;
	mut_val = 50;
}
challenge icon

Challenge

Beginner

Fix the given code so that it will run without errors.

Cheat sheet

When shadowing a variable in Rust, the new variable is completely independent and needs its own mutability declaration. Shadowing does not inherit mutability from the original variable.

let mut mut_val = 7;
// Original variable is mutable
{ 
    let mut_val = 8;
    // This shadows the outer mut_val but is immutable
      
    mut_val = 50;
    // Error: mut_val is not mutable in this scope
}

To fix this, add mut to the shadowing variable:

{
    let mut mut_val = 8;
    mut_val = 50; // Now this works
}

Try it yourself

fn main() {
    // Fix this code to make it work
    let number = 42;
    {
        let number = number;
        println!("number is {}", number);
        number = 100;  // This will cause an error
        println!("number is {}", number);
    }
    println!("number is {}", number);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals