0
0
Rustprogramming~20 mins

If expression in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust If Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using an if expression?

Consider this Rust code snippet. What will it print?

Rust
fn main() {
    let x = 7;
    let y = if x > 5 { "big" } else { "small" };
    println!("{}", y);
}
Abig
Bsmall
Ctrue
D7
Attempts:
2 left
๐Ÿ’ก Hint

Remember, the if expression returns a value based on the condition.

๐Ÿง  Conceptual
intermediate
1:30remaining
What type must both branches of an if expression have in Rust?

In Rust, when using an if expression to assign a value, what must be true about the types of the values in the if and else branches?

AThey must be the same type.
BThey can be any types, Rust will convert automatically.
CThey must both be integers.
DThey must both be strings.
Attempts:
2 left
๐Ÿ’ก Hint

Think about how Rust enforces type safety.

โ“ Predict Output
advanced
2:00remaining
What does this Rust code print?

Analyze the following Rust code and select the output it produces.

Rust
fn main() {
    let a = 10;
    let b = 20;
    let max = if a > b { a } else { b };
    println!("{}", max);
}
A10
B20
Ca
Db
Attempts:
2 left
๐Ÿ’ก Hint

The if expression chooses the bigger number.

๐Ÿ”ง Debug
advanced
2:00remaining
What error does this Rust code produce?

Look at this Rust code snippet. What error will the compiler show?

Rust
fn main() {
    let x = 5;
    let y = if x > 3 { 10 } else { "small" };
    println!("{}", y);
}
Ano error, prints 10
Bunused variable warning
Cmismatched types error
Dmissing semicolon error
Attempts:
2 left
๐Ÿ’ก Hint

Check the types returned by each branch of the if expression.

๐Ÿš€ Application
expert
2:30remaining
How many items does this Rust vector contain after running?

Consider this Rust code using an if expression inside a vector initialization. How many elements does the vector v have?

Rust
fn main() {
    let condition = true;
    let v = vec![1, 2, if condition { 3 } else { 4 }];
    println!("{}", v.len());
}
A2
B4
C1
D3
Attempts:
2 left
๐Ÿ’ก Hint

Count all elements added to the vector.