Understanding Mutability in Rust
What the reader will be able to do: Understand how mutability works in Rust and why it's essential for modifying data.
Prerequisites
- Basic knowledge of variables and data types
- Familiarity with the previous Rust tutorials (structs, functions)
- Understanding of ownership basics
Key Concepts
1. Immutable by Default
In Rust, variables are immutable by default. This means you cannot change their values after initialization:
let x = 5;
// x = 6; // This would cause a compilation error!
2. Mutable Variables
To allow changes, you must explicitly declare a variable as mutable:
let mut x = 5;
x = 6; // This is allowed!
println!("x is {}", x);
3. Why Mutability Matters
Mutability enables:
- Modifying data structures (like structs)
- Updating loop counters
- Changing function parameters (via references)
4. Mutability in Functions
You can pass mutable references to functions to modify the original data:
fn increment(x: &mut i32) {
*x += 1;
}
fn main() {
let mut num = 5;
increment(&mut num);
println!("num is {}", num); // Output: num is 6
}
Common Pitfalls
- Forgetting
mutwhen you need to change a variable - Trying to modify immutable references (
&i32instead of&mut i32) - Confusing variable mutability with data structure mutability
To Go Further
- Learn about Rust's
CellandRefCellfor interior mutability - Explore how
Box<T>andRc<T>interact with mutability - Study the difference between
mutandconstin function parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|