0
0
Rustprogramming~10 mins

If–else expression in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If–else expression
Evaluate condition
Condition true?
NoExecute else block
Use else result
Execute if block
Use if result
Continue with result
The program checks a condition. If true, it runs the 'if' block and uses its result. Otherwise, it runs the 'else' block and uses that result.
Execution Sample
Rust
let number = 7;
let result = if number % 2 == 0 {
    "even"
} else {
    "odd"
};
println!("{} is {}", number, result);
This code checks if 'number' is even or odd and stores the string result, then prints it.
Execution Table
StepActionConditionCondition ResultBlock ExecutedResult Value
1Evaluate condition number % 2 == 07 % 2 == 0falseelse"odd"
2Assign result variableN/AN/AN/A"odd"
3Print outputN/AN/AN/A7 is odd
💡 Condition is false, so else block runs; program prints '7 is odd' and ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
number7777
resultuninitializeduninitialized"odd""odd"
Key Moments - 2 Insights
Why does the else block run even though the condition uses '=='?
Because the condition '7 % 2 == 0' evaluates to false (7 divided by 2 leaves remainder 1), so the else block runs as shown in execution_table step 1.
Is the if–else expression itself a value?
Yes, the if–else expression returns a value from either block, which is assigned to 'result' as shown in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 2?
A"even"
B"odd"
C7
Duninitialized
💡 Hint
Check the 'Result Value' column in execution_table row for step 2.
At which step does the program decide which block to execute?
AStep 1
BStep 3
CStep 2
DAfter printing
💡 Hint
Look at the 'Condition Result' and 'Block Executed' columns in execution_table.
If 'number' was 8 instead of 7, what would 'result' be after step 2?
A"odd"
B8
C"even"
Duninitialized
💡 Hint
Think about the condition 'number % 2 == 0' when number is 8, and check execution_table logic.
Concept Snapshot
If–else expression in Rust:
let result = if condition {
    value_if_true
} else {
    value_if_false
};
It evaluates condition, runs one block, and returns its value.
Useful for choosing values based on conditions.
Full Transcript
This Rust code uses an if–else expression to check if a number is even or odd. It evaluates the condition 'number % 2 == 0'. If true, it returns "even"; otherwise, it returns "odd". The returned value is stored in 'result'. Finally, it prints the number and whether it is even or odd. The execution table shows the condition evaluation, block chosen, and final output. Variables 'number' and 'result' change as the program runs. This example helps understand how if–else expressions return values in Rust.