0
0
Rustprogramming~5 mins

Match overview in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the match expression in Rust?
The match expression in Rust allows you to compare a value against a series of patterns and execute code based on which pattern matches. It's similar to a switch statement but more powerful and exhaustive.
Click to reveal answer
beginner
How does Rust ensure all cases are handled in a match expression?
Rust requires that match expressions be exhaustive, meaning all possible cases must be covered. If not, the compiler will give an error. You can use a catch-all pattern _ to handle any remaining cases.
Click to reveal answer
beginner
What is the purpose of the underscore _ pattern in a match?
The underscore _ pattern acts as a wildcard that matches any value not matched by previous arms. It is used as a catch-all to ensure exhaustiveness without specifying every possible value.
Click to reveal answer
intermediate
Can match arms bind variables? Give an example.
Yes, match arms can bind variables to parts of the matched value. For example:<br>
match some_option {
    Some(x) => println!("Value is {}", x),
    None => println!("No value"),
}
Click to reveal answer
beginner
What happens if no match arm matches and there is no catch-all?
The Rust compiler will produce an error because match expressions must be exhaustive. You must handle all possible cases or include a catch-all _ arm.
Click to reveal answer
What keyword is used in Rust to compare a value against multiple patterns?
Amatch
Bswitch
Ccase
Dselect
What does the underscore _ pattern represent in a match?
AA variable binding
BA wildcard matching any value
CA specific value
DAn error case
What will happen if a match expression is not exhaustive?
AIt will ignore unmatched cases silently
BIt will run but skip unmatched cases
CIt will panic at runtime
DIt will cause a compiler error
Can you bind variables inside match arms?
AYes, to parts of the matched value
BOnly in the catch-all arm
COnly constants can be used
DNo, variables cannot be bound
Which of these is a valid match arm pattern?
Acase x
Bdefault
CSome(x)
Dswitch(x)
Explain how the match expression works in Rust and why it is useful.
Think about how you decide what to do based on different cases.
You got /4 concepts.
    Describe the role of the underscore _ pattern in a match expression.
    It’s like saying 'anything else' in a list of options.
    You got /4 concepts.