0
0
Rustprogramming~20 mins

Using if as expression in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
If Expression Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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);
}
A100
B50
CCompilation error
D10
Attempts:
2 left
๐Ÿ’ก Hint
Remember that if in Rust can return a value and be assigned to a variable.
โ“ Predict Output
intermediate
2: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);
}
ACompilation error due to mismatched types
B5
C"five"
DRuntime panic
Attempts:
2 left
๐Ÿ’ก Hint
Both branches of an if expression must have the same type in Rust.
๐Ÿ”ง Debug
advanced
2: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);
}
APrints "small"
BPrints "big"
CCompilation error: missing else branch for if expression
DRuntime panic due to uninitialized variable
Attempts:
2 left
๐Ÿ’ก Hint
If expressions must cover all cases to produce a value.
๐Ÿง  Conceptual
advanced
2: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?
AIt prevents the use of else blocks in the code.
BIt forces all conditions to be true before executing code.
CIt disables the use of loops inside if blocks.
DIt allows assigning the result of the if directly to a variable, making code concise and expressive.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how expressions can produce values.
โ“ Predict Output
expert
3: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);
}
A7
B6
C0
DCompilation error due to shadowing
Attempts:
2 left
๐Ÿ’ก Hint
Remember that inner let shadows outer variables and if expressions return values.