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
let to declare variables, but by default they are immutable.mut after let makes the variable mutable.let mut for mutable variables [OK]let mut makes variables changeable [OK]x with value 5 in Rust?let comes first, then mut to mark mutability.let mut x = 5; which is correct. Others have wrong order or invalid keywords.let mut variable = value; [OK]let mut in that order [OK]fn main() {
let mut count = 1;
count = count + 2;
println!("{}", count);
}count starts at 1 and is mutable.count becomes 3.fn main() {
let x = 10;
x = 20;
println!("{}", x);
}x is declared without mut, so it is immutable.x = 20; tries to change an immutable variable, causing a compile error.mut to allow variable reassignment [OK]fn main() {
let mut counter = 0;
increment(&mut counter);
increment(&mut counter);
println!("{}", counter);
}
fn increment(count: &mut i32) {
*count += 1;
}let mut counter = 0;.increment takes a mutable reference and increases the value by 1 each call.let mut and mutable references to update variables [OK]Pass the test and this pattern moves unknown