Challenge - 5 Problems
If Expression Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of if expression with integer values
What is the output of this Rust code snippet?
Rust
fn main() {
let x = 10;
let y = if x > 5 { 100 } else { 50 };
println!("{}", y);
}Attempts:
2 left
๐ก Hint
Remember that if in Rust can return a value and be assigned to a variable.
โ Incorrect
Since x is 10, which is greater than 5, the if expression returns 100, which is assigned to y and printed.
โ Predict Output
intermediate2:00remaining
Using if expression with different types
What error or output does this Rust code produce?
Rust
fn main() {
let condition = true;
let value = if condition { 5 } else { "five" };
println!("{:?}", value);
}Attempts:
2 left
๐ก Hint
Both branches of an if expression must have the same type in Rust.
โ Incorrect
The if expression branches return different types: integer and string slice, causing a compilation error.
๐ง Debug
advanced2:00remaining
Identify the error in if expression usage
What is the error in this Rust code snippet?
Rust
fn main() {
let number = 7;
let result = if number > 5 {
"big"
} else if number < 5 {
"small"
};
println!("{}", result);
}Attempts:
2 left
๐ก Hint
If expressions must cover all cases to produce a value.
โ Incorrect
The if expression lacks an else branch for the case when number == 5, so result is not assigned a value, causing a compilation error.
๐ง Conceptual
advanced2:00remaining
Why use if as an expression in Rust?
Which of the following best explains why Rust uses if as an expression rather than a statement?
Attempts:
2 left
๐ก Hint
Think about how expressions can produce values.
โ Incorrect
Using if as an expression lets you assign its result to variables, which makes code shorter and clearer.
โ Predict Output
expert3:00remaining
Output of nested if expressions with shadowing
What is the output of this Rust program?
Rust
fn main() {
let x = 3;
let y = if x > 2 {
let x = x * 2;
if x > 5 { x } else { x + 1 }
} else {
0
};
println!("{}", y);
}Attempts:
2 left
๐ก Hint
Remember that inner let shadows outer variables and if expressions return values.
โ Incorrect
x is 3 > 2 true, so let x = 3 * 2 = 6 (shadowing outer x). Inner if 6 > 5 true returns 6, so y = 6 printed.