0
0
Rustprogramming~5 mins

Matching multiple patterns in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does matching multiple patterns with the | operator in Rust mean?
It means you can check if a value matches any one of several patterns in a single match arm, using the | symbol to separate patterns.
Click to reveal answer
beginner
How do you write a match arm that matches the values 1, 2, or 3 in Rust?
You write:
1 | 2 | 3 => { /* code here */ }
This means if the value is 1, 2, or 3, the code runs.
Click to reveal answer
intermediate
Can you bind variables when matching multiple patterns with | in Rust?
No, you cannot bind variables directly in multiple patterns combined with |. Each pattern must be independent without variable bindings.
Click to reveal answer
intermediate
What happens if you try to use variable bindings in multiple patterns combined with | in Rust?
Rust will give a compile error because it cannot decide which pattern's variable to bind. You must separate those cases into different arms.
Click to reveal answer
beginner
Why is matching multiple patterns useful in Rust?
It lets you write cleaner and shorter code by grouping cases that should do the same thing, avoiding repetition.
Click to reveal answer
Which symbol is used to match multiple patterns in one match arm in Rust?
A|
B&
C&&
D||
What will this Rust code print?<br>
let x = 2;<br>match x {<br>  1 | 2 | 3 => println!("Matched 1, 2, or 3"),<br>  _ => println!("No match"),<br>}
ANothing
BNo match
CCompile error
DMatched 1, 2, or 3
Can you write this in one match arm?<br>
Some(x) => println!("Got {}", x),<br>None => println!("No value")
AYes, using | between Some(x) and None
BYes, by combining with &
CNo, because Some(x) binds a variable and None does not
DNo, because None is not a pattern
What error occurs if you try to bind variables in multiple patterns combined with |?
ASyntax error: unexpected token
BCannot bind variable to multiple patterns
CRuntime panic
DNo error
Why use multiple patterns in one match arm?
ATo handle several cases with the same code
BTo improve runtime speed
CTo bind variables to all patterns
DTo avoid using match
Explain how to match multiple patterns in one match arm in Rust and when it is useful.
Think about grouping values that need the same action.
You got /3 concepts.
    Describe the limitation of variable bindings when matching multiple patterns with | in Rust.
    Consider why Rust cannot decide which variable to bind.
    You got /3 concepts.