0
0
Rustprogramming~5 mins

If–else expression in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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 };
AAssigns 5 to x
BAssigns 20 to x because 5 > 3 is false
CCauses a compile error
DAssigns 10 to x because 5 > 3 is true
In Rust, what type must both branches of an if–else expression return?
AThey can return any types
BThey must return the same type
COne branch returns a type, the other returns unit
DThey must return integers
What is the value of this expression if the condition is false?<br>
if false { 1 } else { 2 }
A2
B1
C()
DCompile error
What happens if you write:<br>
let x = if true { 5 };
?
ACompile error because else is missing
Bx is ()
Cx is uninitialized
Dx is 5
Why is if–else useful as an expression in Rust?
ABecause it is faster than other languages
BBecause it can only run statements
CBecause it returns a value that can be assigned
DBecause it does not need braces
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.