0
0
Rustprogramming~5 mins

Using if as expression in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AA loop inside the <code>if</code>
BA semicolon after <code>if</code>
CA return statement
DAn <code>else</code> block
What type must the if and else blocks return when used as an expression?
AThey must return integers
BThey can return any types
CThey must return the same type
DThey must return booleans
What is the value of x after this code?<br>
let x = if true { 10 } else { 20 };
A10
B20
Ctrue
DCompile error
Can you use if as an expression without assigning its value to a variable?
AYes, but it’s uncommon
BNo, it must always be assigned
CYes, <code>if</code> can be used as a statement only
DNo, <code>if</code> is only an expression
What happens if the if block returns an integer and the else block returns a string?
ARust converts the string to integer
BRust throws a compile-time error
CThe program runs but with warnings
DThe <code>else</code> block is ignored
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.