0
0
Rustprogramming~5 mins

Match expression deep dive in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a match expression in Rust?
A match expression lets you compare a value against many patterns and execute code based on which pattern matches. It's like a smart switch that checks all possibilities.
Click to reveal answer
beginner
How does Rust handle unmatched patterns in a match expression?
Rust requires all possible cases to be covered in a match. If some cases are missing, the code won't compile. You can use a catch-all pattern _ to cover any leftover cases.
Click to reveal answer
intermediate
What is the role of the @ operator in a match pattern?
The @ operator lets you name a value while also testing it against a pattern. For example, id @ 1..=5 means "match values from 1 to 5 and call it id".
Click to reveal answer
beginner
Explain how to match multiple patterns in one arm of a match expression.
You can match multiple patterns separated by | in one arm. For example, 1 | 2 | 3 => println!("One to three") runs the same code for 1, 2, or 3.
Click to reveal answer
beginner
What happens if you forget to handle a pattern in a match expression?
Rust will give a compile-time error saying the match is not exhaustive. This helps avoid bugs by forcing you to handle all possible cases.
Click to reveal answer
What does the underscore _ pattern do in a match expression?
AMatches only negative numbers
BMatches any value not matched by previous patterns
CMatches only zero
DCauses a compile error
How do you bind a matched value to a variable inside a match arm?
AYou cannot bind values in <code>match</code>
BUsing <code>let</code> inside the arm
CUsing <code>match</code> keyword again
DUsing the <code>@</code> operator, like <code>id @ 1..=5</code>
Which of these is a valid way to match multiple values in one match arm?
A1 | 2 | 3 => println!("Matched")
B1 & 2 & 3 => println!("Matched")
C1, 2, 3 => println!("Matched")
D1 + 2 + 3 => println!("Matched")
What will happen if a match expression does not cover all possible cases?
ACompile-time error
BRuntime panic
CIt will ignore missing cases
DIt will print a warning but compile
In a match expression, what does this arm do? Some(x) => println!("Value: {}", x)
ACauses a syntax error
BMatches any value and ignores it
CMatches an Option with a value and binds it to x
DMatches None variant
Explain how Rust's match expression ensures all cases are handled and why this is helpful.
Think about what happens if you forget a case.
You got /4 concepts.
    Describe how to use the @ operator in a match pattern and give an example.
    It lets you name the value while matching it.
    You got /3 concepts.