In Rust, pattern matching is often preferred over long if-else chains. Why is this the case?
Think about how pattern matching helps with clarity and completeness.
Pattern matching lets you write clear code that handles all possible cases explicitly. It is more readable and helps avoid missing cases compared to if-else chains.
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?
Look at the value of number and which arm matches it.
The value 3 matches the third arm, so it prints "Three".
Look at this Rust code:
let value = Some(5);
match value {
Some(x) => println!("Value is {}", x),
}What error will the compiler show?
Think about whether all possible cases of Option are covered.
The match is missing the None case, so the compiler complains about non-exhaustive patterns.
Which of these Rust code snippets correctly uses a pattern guard in a match arm?
Remember the syntax for pattern guards uses if after the pattern.
Option C correctly uses n if n > 0 as a pattern guard. Option C is invalid syntax. Option C uses a colon instead of =>. Option C has extra parentheses but is still valid syntax in Rust, but the question is about the correct standard style, so B is preferred.
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?
Count the number of variants in the enum.
There are three variants: Red, Yellow, and Green. To cover all without a wildcard, you need three arms.