0
0
Rustprogramming~10 mins

Immutable variables in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Immutable variables
Declare variable with let
Variable is immutable by default
Try to change variable value
Compiler error: cannot assign to immutable variable
Use variable as is or declare mutable with let mut
In Rust, variables declared with let are immutable by default. Trying to change their value causes a compile error. To change a variable, declare it mutable with let mut.
Execution Sample
Rust
fn main() {
    let x = 5;
    // x = 6; // error: cannot assign to immutable variable
    println!("x = {}", x);
}
This code declares an immutable variable x with value 5 and prints it. Trying to assign a new value to x causes a compile error.
Execution Table
StepActionVariableValueResult/Output
1Declare x with let x = 5;x5x is set to 5
2Attempt to assign x = 6;x5Compile error: cannot assign to immutable variable
3Print xx5Output: x = 5
💡 Execution stops at compile error on step 2 because x is immutable
Variable Tracker
VariableStartAfter Step 1After Step 2Final
xundefined55 (unchanged, assignment failed)5
Key Moments - 2 Insights
Why can't we assign a new value to x after declaring it with let?
Because variables declared with let are immutable by default in Rust, so the compiler prevents changing their value as shown in step 2 of the execution_table.
How can we make a variable mutable so we can change its value?
By declaring it with let mut instead of let, which tells Rust the variable can be changed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x after step 1?
Aundefined
B6
C5
D0
💡 Hint
Check the 'Value' column for step 1 in the execution_table
At which step does the compiler error occur?
AStep 1
BStep 2
CStep 3
DNo error
💡 Hint
Look at the 'Result/Output' column in the execution_table for the error message
If we change 'let x = 5;' to 'let mut x = 5;', what happens at step 2?
Ax changes to 6 successfully
BProgram crashes
CCompile error remains
Dx remains 5
💡 Hint
Recall that 'let mut' allows variable reassignment, so step 2 assignment succeeds
Concept Snapshot
Rust variables declared with let are immutable by default.
Trying to assign a new value causes a compile error.
Use let mut to declare mutable variables.
Immutable variables help prevent bugs by avoiding unintended changes.
Full Transcript
In Rust, when you declare a variable with let, it is immutable by default. This means you cannot change its value later. For example, if you write let x = 5;, x holds the value 5 and cannot be changed. If you try to assign x = 6;, the compiler will give an error and stop the program from compiling. To allow changing a variable's value, you must declare it mutable using let mut x = 5;. Then you can assign new values to x. This behavior helps keep your code safe and predictable by preventing accidental changes to variables.