0
0
Rustprogramming~20 mins

Why pattern matching is needed in Rust - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Pattern Matching Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use pattern matching instead of if-else chains?

In Rust, pattern matching is often preferred over long if-else chains. Why is this the case?

APattern matching allows checking multiple conditions in a clear, concise way and ensures all cases are handled.
BPattern matching is slower but easier to write than if-else chains.
CIf-else chains can only check one condition at a time, pattern matching can check none.
DPattern matching is only used for error handling, not for general conditions.
Attempts:
2 left
💡 Hint

Think about how pattern matching helps with clarity and completeness.

Predict Output
intermediate
2:00remaining
What is the output of this Rust code using pattern matching?

Consider this Rust code snippet:

let number = 3;
match number {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    _ => println!("Other"),
}

What will it print?

AOther
BTwo
COne
DThree
Attempts:
2 left
💡 Hint

Look at the value of number and which arm matches it.

🔧 Debug
advanced
2:00remaining
What error does this Rust pattern matching code produce?

Look at this Rust code:

let value = Some(5);
match value {
    Some(x) => println!("Value is {}", x),
}

What error will the compiler show?

AError: match arms have different types
BError: non-exhaustive patterns, missing None case
CError: variable x not found
DNo error, code compiles fine
Attempts:
2 left
💡 Hint

Think about whether all possible cases of Option are covered.

📝 Syntax
advanced
2:00remaining
Which option correctly uses pattern matching with guards in Rust?

Which of these Rust code snippets correctly uses a pattern guard in a match arm?

A
match x {
    n > 0 => println!("Positive"),
    _ => println!("Non-positive"),
}
B
match x {
    n if n > 0: println!("Positive"),
    _ => println!("Non-positive"),
}
C
match x {
    n if n > 0 => println!("Positive"),
    _ => println!("Non-positive"),
}
D
match x {
    n if (n > 0) => println!("Positive"),
    _ => println!("Non-positive"),
}
Attempts:
2 left
💡 Hint

Remember the syntax for pattern guards uses if after the pattern.

🚀 Application
expert
2:00remaining
How many arms are needed to exhaustively match this enum?

Given this Rust enum:

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

How many arms are needed in a match statement to cover all cases without using a wildcard arm?

A3
B2
C1
D4
Attempts:
2 left
💡 Hint

Count the number of variants in the enum.