
Pattern Matching
Match expressions, if let, while let, destructuring, guards, @ bindings, exhaustiveness
1What is the correct syntax for a basic match expression in Rust?
What is the correct syntax for a basic match expression in Rust?
回答
The match expression in Rust uses the match keyword followed by the value to analyze, then curly braces containing the different arms (patterns) separated by commas. Each arm uses the pattern followed by => and the code to execute. This syntax allows the compiler to verify that all possible cases are covered.
2Which pattern should be used to capture all remaining values in a match?
Which pattern should be used to capture all remaining values in a match?
回答
The _ (underscore) pattern is the catch-all pattern in Rust. It matches any value without binding it to a variable. Alternatively, using a variable name (like other or n) captures the value. The _ is preferred when the value is not used as it clearly indicates the intent.
3How does if let work compared to match?
How does if let work compared to match?
回答
if let is a shorthand syntax for a match that handles only one pattern and ignores the others. Instead of writing a full match with a _ catch-all arm, if let allows extracting a value concisely when only a specific case matters. It is particularly useful with Option and Result.
What is exhaustiveness in the context of Rust pattern matching?
How to destructure a tuple in a pattern match?
+15 面接問題