Variables, Mutability & Shadowing
In Rust, variables are immutable by default. This design choice guarantees thread safety and prevents unintended bugs.
1 Mutability & Variable Shadowing
Rust variables support two key characteristics:
- Mutability (`let mut`): To allow variable values to change, you must explicitly declare mutability using the `mut` keyword: `let mut score = 10;`.
- Variable Shadowing: You can declare a new variable with the same name as an existing variable using the `let` keyword. The new variable "shadows" the previous one, allowing you to change its value and even its data type while keeping the variable name.
2 Shadowing Code
Let's run a program exploring mutability controls and variable shadowing:
Rust — Variables
▶ Run Code
fn main() {
// Immutable variable
let x = 5;
println!("x: {}", x);
// Mutable variable
let mut y = 10;
y = 15;
println!("y: {}", y);
// Shadowing: redeclaring with 'let'
let spaces = " "; // String type
let spaces = spaces.len(); // Shadowed variable is now an integer type
println!("Spaces length: {}", spaces);
}
3 Code Challenge
Challenge: Declare a variable `let val = 100;`. Write a statement that shadows it to hold the value `"One Hundred"`. Print it to verify shadowing works.