Concept Flow - Mutable variables
Declare variable with mut
Assign initial value
Use variable
Change value
Use updated variable
End
This flow shows how a mutable variable is declared, assigned, used, changed, and used again in Rust.
fn main() {
let mut x = 5;
println!("x = {}", x);
x = 10;
println!("x = {}", x);
}| Step | Action | Variable x | Output |
|---|---|---|---|
| 1 | Declare mutable variable x with value 5 | 5 | |
| 2 | Print x | 5 | x = 5 |
| 3 | Change x to 10 | 10 | |
| 4 | Print x | 10 | x = 10 |
| 5 | End of program | 10 |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| x | undefined | 5 | 10 | 10 |
Mutable variables in Rust: - Declare with 'let mut variable = value;' - Allows changing the variable's value later - Variables are immutable by default - Changing without 'mut' causes compile error - Use println! to see variable values