Recall & Review
beginner
What is an if–else expression in Rust?
An if–else expression in Rust lets you choose between two paths based on a condition. It evaluates to a value, so you can assign its result to a variable.
Click to reveal answer
beginner
How do you write a simple if–else expression in Rust?
You write it like this:<br><pre>let x = if condition { value1 } else { value2 };</pre><br>The variable x gets value1 if the condition is true, otherwise value2.Click to reveal answer
intermediate
Can if–else expressions in Rust return different types?
No. Both branches of an if–else expression must return the same type because Rust needs to know the exact type of the expression's result.
Click to reveal answer
intermediate
What happens if you omit the else branch in an if expression?
If you omit else, the if expression returns () (unit type) when the condition is false. This can cause type mismatch if you try to assign it to a variable expecting another type.
Click to reveal answer
beginner
Why is if–else called an expression in Rust, not just a statement?
Because it produces a value that can be used in assignments or other expressions. This makes Rust code concise and expressive.
Click to reveal answer
What does this Rust code do?<br>
let x = if 5 > 3 { 10 } else { 20 };✗ Incorrect
Since 5 is greater than 3, the condition is true, so x gets 10.
In Rust, what type must both branches of an if–else expression return?
✗ Incorrect
Both branches must return the same type so Rust knows the expression's type.
What is the value of this expression if the condition is false?<br>
if false { 1 } else { 2 }✗ Incorrect
The else branch runs when the condition is false, so the value is 2.
What happens if you write:<br>
let x = if true { 5 };?✗ Incorrect
Rust requires else branch for if used as an expression to ensure both branches return a value.
Why is if–else useful as an expression in Rust?
✗ Incorrect
If–else expressions return values, allowing concise and clear code.
Explain how an if–else expression works in Rust and why both branches must return the same type.
Think about how Rust needs to know the type of the whole expression.
You got /4 concepts.
Describe what happens if you use an if expression without an else branch when assigning to a variable.
Consider what Rust returns when the condition is false and no else is given.
You got /4 concepts.