0
0
Rustprogramming~10 mins

Mutable variables in Rust - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Rust
fn main() {
    let mut x = 5;
    println!("x = {}", x);
    x = 10;
    println!("x = {}", x);
}
This code declares a mutable variable x, prints it, changes its value, and prints it again.
Execution Table
StepActionVariable xOutput
1Declare mutable variable x with value 55
2Print x5x = 5
3Change x to 1010
4Print x10x = 10
5End of program10
💡 Program ends after printing updated value of x.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
xundefined51010
Key Moments - 2 Insights
Why do we need to write 'mut' before the variable name?
In Rust, variables are immutable by default. Writing 'mut' allows the variable to be changed later, as shown in steps 1 and 3 of the execution_table.
What happens if we try to change x without 'mut'?
Without 'mut', Rust will give a compile error when trying to assign a new value to x, because variables are immutable by default. This is why step 3 requires 'mut' in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after step 3?
A10
Bundefined
C5
D0
💡 Hint
Check the 'Variable x' column at step 3 in the execution_table.
At which step is the first time x is printed?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Output' column in the execution_table to find when x is printed first.
If we remove 'mut' from the declaration, what will happen at step 3?
Ax changes to 10 successfully
BCompile error occurs
Cx remains 5 silently
DProgram prints an error at runtime
💡 Hint
Refer to key_moments about mutability and step 3 in the execution_table.
Concept Snapshot
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
Full Transcript
This example shows how to use mutable variables in Rust. First, we declare a variable x with 'let mut x = 5;'. This means x can be changed later. We print x, which shows 5. Then we change x to 10 and print it again, showing 10. Without 'mut', Rust would not allow changing x. This teaches that variables are immutable by default and 'mut' is needed to make them mutable.