0
0
Rustprogramming~10 mins

If expression in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If expression
Evaluate condition
Condition true?
NoExecute else block
Result from else
Execute if block
Result from if
Use result
The if expression evaluates a condition. If true, it runs the if block and returns its value; otherwise, it runs the else block and returns that value.
Execution Sample
Rust
let x = 5;
let y = if x > 3 { 10 } else { 20 };
println!("y = {}", y);
This code sets y to 10 if x is greater than 3, otherwise 20, then prints y.
Execution Table
StepCondition (x > 3)Branch TakenValue from BranchVariable y
15 > 3True (if block)1010
2End of if expression--10
3Print y--Outputs: y = 10
💡 Condition is true, so if block runs and y is set to 10.
Variable Tracker
VariableStartAfter if expressionFinal
x555
yuninitialized1010
Key Moments - 2 Insights
Why does the if expression return a value?
In Rust, if is an expression, not just a statement. It returns the value from the executed branch, as shown in the execution_table step 1 where y gets the value 10.
What happens if the else block is missing?
If else is missing and the condition is false, Rust will give a compile error because the if expression must return a value in all cases. This is why the else branch is needed to cover the false case.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value does y have after the if expression?
A5
B10
C20
Duninitialized
💡 Hint
Check the 'Variable y' column in the first row of the execution_table.
At which step does the program decide which branch to take?
AStep 3
BStep 2
CStep 1
DBefore Step 1
💡 Hint
Look at the 'Condition (x > 3)' and 'Branch Taken' columns in the execution_table.
If x was 2 instead of 5, what would y be after the if expression?
A20
B10
C2
Duninitialized
💡 Hint
If condition is false, else branch value is used, see execution_table logic.
Concept Snapshot
if expression syntax:
if condition { expr1 } else { expr2 }

Evaluates condition:
- if true, returns expr1
- else, returns expr2

Must cover all cases (else required)
Returns a value usable in assignments.
Full Transcript
This visual execution shows how Rust's if expression works. First, the condition x > 3 is checked. Since x is 5, the condition is true, so the if block runs and returns 10. This value is assigned to y. The else block is skipped. Finally, y is printed as 10. The key point is that if is an expression returning a value, not just a statement. The else block is necessary to cover the false case and ensure the expression always returns a value.