0
0
Rustprogramming~10 mins

Using if as expression in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Using if as expression
Evaluate condition
Yes
Evaluate 'if' block expression
Use value
No
Evaluate 'else' block expression
Use value
The if statement in Rust can be used as an expression that returns a value depending on the condition.
Execution Sample
Rust
let number = 7;
let result = if number % 2 == 0 { "even" } else { "odd" };
println!("{} is {}", number, result);
This code checks if a number is even or odd and stores the result as a string using if as an expression.
Execution Table
StepConditionCondition ResultBranch TakenExpression ValueVariable 'result'
1number % 2 == 07 % 2 == 0 → 1 == 0 → falseelse"odd""odd"
2Print statement---Prints: 7 is odd
💡 Condition is false, so else branch value 'odd' is assigned to 'result'.
Variable Tracker
VariableStartAfter if expressionFinal
number777
resultuninitialized"odd""odd"
Key Moments - 2 Insights
Why does 'result' get the value from the else block?
Because the condition 'number % 2 == 0' is false (7 is not divisible by 2), the else block is executed and its value 'odd' is assigned to 'result' as shown in execution_table row 1.
Can if expression return different types in each branch?
No, both branches must return the same type because the if expression must have a single consistent type for the variable it assigns to, as seen with both branches returning &str.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 1?
A"even"
B"odd"
C7
Duninitialized
💡 Hint
Check the 'Variable result' column in execution_table row 1.
At which step does the condition evaluate to false?
AStep 1
BStep 2
CNo step, condition is true
DCondition is not evaluated
💡 Hint
Look at the 'Condition Result' column in execution_table row 1.
If number was 8 instead of 7, what would 'result' be after step 1?
A8
B"odd"
C"even"
Duninitialized
💡 Hint
Think about the condition 'number % 2 == 0' with number = 8 and check which branch is taken.
Concept Snapshot
Using if as expression in Rust:
let result = if condition { value_if_true } else { value_if_false };
- The if expression returns a value.
- Both branches must return the same type.
- Useful for concise conditional assignments.
Full Transcript
In Rust, if can be used as an expression that returns a value. The condition is evaluated first. If true, the value from the if block is returned; if false, the else block's value is returned. Both branches must return the same type. This allows assigning the result of the if expression directly to a variable. For example, checking if a number is even or odd and storing the string result in a variable. The execution table shows the condition evaluation, branch taken, and the value assigned. The variable tracker shows how 'result' changes from uninitialized to the final value. This approach makes code concise and clear.