Advanced 14 min readModule: Module 2: Variables, Mutability & Shadowing
Immutability by Default & Variable Shadowing
Understand why variables in Rust are immutable by default and how variable shadowing enables safe transformations.
What You Will Learn in This Lesson
- Why Rust defaults to immutable variables (let x = 5)
- Explicit mutability with 'let mut'
- Reusing variable names and changing types with Variable Shadowing
Introduction & Core Concept
In Rust, variables are immutable by default. This is one of many nudges Rust gives you to write code in a way that takes advantage of the safety and easy concurrency that Rust offers.
WHY DOES THIS MATTER IN THE REAL WORLD?
Default immutability prevents accidental mutations across complex concurrent threads.
Variable Shadowing & Mutability
rustrust
12345678910fn main() {// Mutable variablelet mut score = 100;score += 50;// Variable Shadowing (transforms type safely)let spaces = " ";let spaces = spaces.len(); // spaces is now usize: 3println!("Score: {}, Spaces count: {}", score, spaces);}
Line-by-Line Technical Breakdown
1Constants (const MAX: u32 = 100) must be annotated with explicit types and evaluated at compile time.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[RUST]
RUST SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Prefer variable shadowing over making variables mutable whenever transforming data.
Lesson Summary & Core Takeaways
- Immutability and shadowing ensure deterministic state transitions.