Beginner Fundamentals
Mutability
When you need a variable whose value can change, declare it with let mut. The mut keyword makes the variable mutable.
Mutable variables
fn main() {
let mut counter = 0;
counter = counter + 1;
counter += 1;
println!("Counter is {}", counter); // 2
}
Without mut, reassigning counter would be a compile error.
Why immutable by default
Rust makes variables immutable by default for good reasons:
- Fewer bugs: values do not change unexpectedly behind your back.
- Easier reasoning: you know a value stays constant once set.
- Safer concurrency: immutable data can be shared across threads without races.
By forcing you to write mut, Rust makes mutation visible and intentional.
Example
fn main() {
let mut temperature = 20.0;
println!("Start: {}", temperature);
temperature = 25.5;
println!("Updated: {}", temperature);
}
Use mut only when change is truly needed; prefer immutability otherwise.