Variables and Mutability | Rust Fundamentals lesson | BraveProgrammer
Lesson 5 of 50
·rust
Variables and Mutability
12 minutes
Course progress10%
Variables and Mutability
One of Rust's core principles is immutability by default. This prevents entire categories of bugs and encourages careful thinking about what data your program modifies.
Immutable Variables
All variables are immutable by default:
fnmain() {
letx = 5;
(\
println!
"x = {}\", x); // prints 5
// x = 6; // ERROR!
}
Trying to modify an immutable variable produces a compiler error. This is a feature, not a limitation—the compiler prevents accidental mutations.
Mutable Variables
Explicitly mark variables as mutable with mut:
fnmain() {
letmut x = 5;
println!(\"x = {}\", x); // prints 5
x = 6;
println!(\"x = {}\", x); // prints 6
}
The mut keyword signals intent: "This variable will change." This self-documents code.
Why Immutability by Default?
Safety
Immutable variables can't change unexpectedly.
Concurrency
Immutable data is thread-safe. Multiple threads safely read immutable values without synchronization.
Reasoning About Code
Immediate clarity about whether a value can change.
Variable Shadowing
Declare a new variable with the same name, creating a new binding:
fnmain() {
letx = 5;
letx = x + 1; // Shadow: new bindingletx = x * 2; // Another shadowprintln!(\"x = {}\", x); // prints 12
}
Shadowing differs from mutability:
Shadowing: Creates new variable (possibly different type)
Mutability: Changes value of same variable
Use shadowing for transformations:
fnmain() {
letinput = \" 42 \";
let input = input.trim(); // Shadow: trimmed string
let input: i32 = input.parse().unwrap(); // Shadow: parse to number
println!(\"Number: {}\", input + 10); // 52
}