0
0
Rustprogramming~10 mins

Why variables are needed in Rust - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why variables are needed
Start Program
Declare Variable
Assign Value
Use Variable in Code
Change Value (Optional)
Use Updated Value
End Program
This flow shows how variables store values to use and change during a program.
Execution Sample
Rust
fn main() {
    let mut age = 10;
    println!("Age is {}", age);
    age = 15;
    println!("New age is {}", age);
}
This Rust code stores a number in a variable, prints it, changes it, and prints again.
Execution Table
StepActionVariable 'age'Output
1Declare mutable variable 'age' with value 1010
2Print 'Age is 10'10Age is 10
3Change 'age' value to 1515
4Print 'New age is 15'15New age is 15
5Program ends15
💡 Program ends after printing updated variable value.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
ageundefined101515
Key Moments - 3 Insights
Why do we need to declare 'mut' before 'age'?
In Rust, variables are immutable by default. Declaring 'mut' allows changing the value later, as shown in steps 3 and 4 of the execution_table.
What happens if we try to change 'age' without 'mut'?
The program will not compile because Rust prevents changing immutable variables. This is why 'mut' is needed to allow reassignment.
Why do we use variables instead of just printing numbers directly?
Variables let us store and reuse values easily. Here, 'age' holds a number that we print and update, making the code flexible and clear.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'age' after step 1?
A10
Bundefined
C15
D0
💡 Hint
Check the 'Variable age' column in row for step 1 in execution_table.
At which step does the variable 'age' change its value?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the 'Action' column in execution_table for when 'age' is reassigned.
If we remove 'mut' from the variable declaration, what will happen?
AThe program will print both ages correctly.
BThe program will not compile due to reassignment error.
CThe variable 'age' will become zero.
DThe program will crash at runtime.
💡 Hint
Recall Rust's rule about immutability and reassignment from key_moments.
Concept Snapshot
Variables store values to use and change in programs.
In Rust, variables are immutable by default.
Use 'mut' to allow changing a variable's value.
Variables make code flexible and readable.
You can print and update variables anytime.
Full Transcript
This example shows why variables are needed in Rust. We start by declaring a mutable variable 'age' with value 10. Then we print it. Next, we change 'age' to 15 and print the new value. Variables let us store data and update it as needed. Rust requires 'mut' to allow changes. Without variables, we would have to write values directly, which is less flexible. This step-by-step trace helps understand how variables hold and change data during program execution.