Recall & Review
beginner
What does it mean that
if can be used as an expression in Rust?In Rust,
if can return a value, so you can assign the result of an if block to a variable. This means if is not just for control flow but also produces a value.Click to reveal answer
beginner
How do you assign a value to a variable using
if as an expression?You write <code>let variable = if condition { value1 } else { value2 };</code>. The variable gets the value from the block that matches the condition.Click to reveal answer
intermediate
What happens if you omit the
else block when using if as an expression?Rust requires an
else block when using if as an expression to ensure both branches return a value. Omitting else causes a compile error.Click to reveal answer
intermediate
Can the blocks inside
if expression return different types?No. Both
if and else blocks must return the same type because the variable assigned expects a single type.Click to reveal answer
beginner
Example: What is the value of <code>result</code> after this code?<br><pre>let number = 7;
let result = if number % 2 == 0 { "even" } else { "odd" };</pre>The value of
result is "odd" because 7 is not divisible by 2, so the else block runs.Click to reveal answer
What must you always include when using
if as an expression in Rust?✗ Incorrect
When using
if as an expression, Rust requires an else block to provide a value for all cases.What type must the
if and else blocks return when used as an expression?✗ Incorrect
Both blocks must return the same type because the expression's value must have a single consistent type.
What is the value of
x after this code?<br>let x = if true { 10 } else { 20 };✗ Incorrect
Since the condition is
true, the if block runs and x is assigned 10.Can you use
if as an expression without assigning its value to a variable?✗ Incorrect
You can use
if as an expression without assignment, but usually it’s used to produce a value for a variable.What happens if the
if block returns an integer and the else block returns a string?✗ Incorrect
Rust requires both blocks to return the same type; otherwise, it causes a compile-time error.
Explain how
if can be used as an expression in Rust and why it is useful.Think about how you can choose a value based on a condition.
You got /4 concepts.
Describe what happens if you forget the
else block when using if as an expression.Rust wants to be sure what value to assign in all cases.
You got /3 concepts.