Variables, Mutability, and Shadowing
Variables, Mutability, and Shadowing
By default, variables in Rust are immutable. Once bound to a value, the binding cannot be modified.
Mutability with mut
To allow mutation, explicitly declare the binding with mut:
fn main() {
let mut counter = 10;
println!("Initial counter: {}", counter);
counter += 5;
println!("Updated counter: {}", counter);
}Variable Shadowing
Rust allows redeclaring a variable with the same name in the same scope using let. This is shadowing:
fn main() {
let spaces = " ";
let spaces = spaces.len(); // Shadows spaces: changes type from &str to usize
println!("Number of spaces: {}", spaces);
}Shadowing creates a new binding, allowing type transformation without requiring distinct variable names.