What Is Variable Shadowing in Rust?

Variable shadowing in Rust allows reusing a variable name to bind a new value, hiding the previous one without requiring mutability.

Variable shadowing in Rust is the ability to declare a new variable with the same name as an existing one, effectively hiding the original value within that scope. This allows you to reuse a variable name for a different value or type without needing to create a new name or make the original variable mutable.

fn main() {
    let x = 5;
    let x = x + 1; // Shadows the previous 'x'
    let x = x * 2; // Shadows the previous 'x' again
    println!("The value of x is: {x}"); // Prints 12
}