0
0
Rustprogramming~5 mins

If expression in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an if expression in Rust?
An if expression in Rust lets you run code only when a condition is true. It can also return a value, making it more than just a decision maker.
Click to reveal answer
beginner
How do you write a simple if expression in Rust?
Use if condition { /* code */ }. For example: <br>if x > 5 { println!("x is big"); }
Click to reveal answer
intermediate
Can if expressions return values in Rust?
Yes! You can assign the result of an <code>if</code> expression to a variable. For example: <br><code>let number = if condition { 5 } else { 10 };</code>
Click to reveal answer
intermediate
What happens if you omit the else branch in an if expression used for assignment?
Rust will give an error because the if expression must return a value in all cases when assigned to a variable.
Click to reveal answer
beginner
How do you write multiple conditions with if in Rust?
Use else if for additional conditions. For example: <br>if x > 5 { ... } else if x == 5 { ... } else { ... }
Click to reveal answer
What does an if expression in Rust return when used in an assignment?
AThe value from the executed branch
BAlways a boolean
CNothing, it cannot return a value
DThe last executed statement in the program
Which of these is a correct way to write an if expression in Rust?
Aif x > 5: { println!("big"); }
Bif (x > 5) then { println!("big"); }
Cif x > 5 print!("big");
Dif x > 5 { println!("big"); }
What error occurs if you assign an if expression without an else branch?
AMissing else branch error
BMismatched types error
CNo error, it's allowed
DSyntax error due to missing semicolon
How do you check multiple conditions in Rust?
AUse multiple <code>if</code> statements without <code>else</code>
BUse <code>switch</code> statement
CUse <code>else if</code> after <code>if</code>
DUse <code>elif</code> keyword
What type must the values returned by all branches of an if expression have?
AThey must all be the same type
BThey can be any types
CThey must be booleans
DThey must be integers
Explain how an if expression works in Rust and how it can be used to assign values.
Think about how you decide between two options and store the result.
You got /5 concepts.
    Describe what happens if you use an if expression without an else branch when assigning to a variable.
    Consider what Rust expects when it needs a value from all paths.
    You got /4 concepts.