Shadowing allows rebinding a variable name using `let` in the same or an inner scope. Unlike mutation, shadowing creates an entirely new variable and can change the type.
fn main() {
let raw_input = " 1024 ";
// Shadow raw_input with parsed integer of a different type:
let raw_input: usize = raw_input.trim().parse().expect("Invalid number");
println!("Parsed bytes: {}", raw_input);
let level = 1;
{
let level = level * 10; // Shadows outer level inside this block
println!("Inner level: {}", level); // 10
}
println!("Outer level: {}", level); // 1 (unchanged!)
}Shadowing is distinct from marking a variable `mut`. When you shadow, the original variable is not overwritten; rather, a brand-new variable binding is created on the stack frame that masks the previous one from the current scope onward.
This idiom eliminates throwaway variable names like `raw_input_str` and `raw_input_int`, keeping naming clean across data transformation pipelines.
Under the hood, the compiler creates two separate stack storage slots. The first binding remains alive until its own lexical scope ends, but the compiler symbol table resolves any subsequent references to the newer binding.
// Stack layout:
// [rbp - 8]: raw_input (&str fat pointer: ptr + len = 16 bytes)
// [rbp - 16]: raw_input (usize integer: 8 bytes)
// The identifier `raw_input` resolves to [rbp - 16] for all following lines.