Bird
Raised Fist0
Rustprogramming~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does using if as an expression in Rust allow you to do?
easy
A. Define functions inside an if statement
B. Only execute code blocks without returning values
C. Assign a value based on a condition directly to a variable
D. Create loops that run while a condition is true

Solution

  1. Step 1: Understand the role of if as expression

    In Rust, if can return a value, unlike some languages where it only controls flow.
  2. Step 2: Recognize assignment usage

    This means you can assign a variable directly using let x = if condition { value1 } else { value2 };.
  3. Final Answer:

    Assign a value based on a condition directly to a variable -> Option C
  4. Quick Check:

    if as expression = assign value [OK]
Hint: Think of if as a value picker, not just a decision maker [OK]
Common Mistakes:
  • Thinking if can't return values
  • Confusing if expression with loops
  • Assuming if can define functions
2. Which of the following is the correct syntax for using if as an expression to assign a value in Rust?
easy
A. let x = if (condition) then 10 else 20;
B. let x = if condition { 10 } else { 20 };
C. let x = if condition: 10 else: 20;
D. let x = if condition { 10 } else 20;

Solution

  1. Step 1: Recall Rust if expression syntax

    Rust uses curly braces for blocks and requires both if and else blocks to be enclosed in braces when returning values.
  2. Step 2: Check each option

    let x = if condition { 10 } else { 20 }; correctly uses if condition { 10 } else { 20 };. Others use invalid syntax like missing braces or keywords.
  3. Final Answer:

    let x = if condition { 10 } else { 20 }; -> Option B
  4. Quick Check:

    Correct Rust if expression syntax = let x = if condition { 10 } else { 20 }; [OK]
Hint: Remember: Rust uses braces {} for both if and else blocks [OK]
Common Mistakes:
  • Omitting braces around else block
  • Using 'then' keyword (not in Rust)
  • Using colons instead of braces
3. What is the output of this Rust code?
let number = 7;
let result = if number % 2 == 0 { "even" } else { "odd" };
println!("{}", result);
medium
A. even
B. 7
C. Compilation error
D. odd

Solution

  1. Step 1: Evaluate the condition

    The condition checks if 7 modulo 2 equals 0. Since 7 % 2 is 1, the condition is false.
  2. Step 2: Determine which branch runs

    Because the condition is false, the else branch runs, returning "odd".
  3. Final Answer:

    odd -> Option D
  4. Quick Check:

    7 is odd = odd [OK]
Hint: Check the condition result carefully before picking output [OK]
Common Mistakes:
  • Assuming 7 % 2 == 0 is true
  • Confusing output with the number itself
  • Expecting a syntax error
4. Identify the error in this Rust code using if as expression:
let x = if true { 5 } else { "five" };
medium
A. Mismatched types in if and else branches
B. Missing semicolon after else block
C. Cannot use if as expression in let binding
D. Condition must be a variable, not a literal

Solution

  1. Step 1: Check types returned by if and else

    The if branch returns an integer 5, the else branch returns a string "five".
  2. Step 2: Understand Rust type rules for if expressions

    Both branches must return the same type because the if expression must have a single consistent type.
  3. Final Answer:

    Mismatched types in if and else branches -> Option A
  4. Quick Check:

    if branches must match types = Mismatched types in if and else branches [OK]
Hint: Ensure both if and else return same type [OK]
Common Mistakes:
  • Ignoring type mismatch errors
  • Thinking semicolon is missing
  • Believing literals can't be conditions
5. You want to assign a variable status based on a score: if score >= 90, status is "Excellent"; if score >= 60, status is "Pass"; otherwise, "Fail". Which Rust code correctly uses nested if expressions to do this?
hard
A. let status = if score >= 90 { "Excellent" } else if score >= 60 { "Pass" } else { "Fail" };
B. let status = if score >= 90 { "Excellent" } else { if score >= 60 { "Pass" } else "Fail" };
C. let status = if score >= 90 { "Excellent" } else if score >= 60 { "Pass" }; else { "Fail" };
D. let status = if score >= 90 { "Excellent" } else { "Pass" } else { "Fail" };

Solution

  1. Step 1: Understand nested if expressions

    Rust supports chaining if and else if expressions to select among multiple conditions.
  2. Step 2: Check syntax correctness

    let status = if score >= 90 { "Excellent" } else if score >= 60 { "Pass" } else { "Fail" }; correctly uses else if and ends with else block. let status = if score >= 90 { "Excellent" } else { if score >= 60 { "Pass" } else { "Fail" } }; nests if inside else but is more verbose. Options C and D have syntax errors.
  3. Final Answer:

    let status = if score >= 90 { "Excellent" } else if score >= 60 { "Pass" } else { "Fail" }; -> Option A
  4. Quick Check:

    Use else if for clean multi-condition if expressions [OK]
Hint: Use else if for multiple conditions, not nested if inside else [OK]
Common Mistakes:
  • Missing else block causing syntax error
  • Incorrect semicolon placement
  • Using multiple else blocks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard