0
0
Rustprogramming~10 mins

Matching multiple patterns in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Matching multiple patterns
Start match expression
Check first pattern
Yes
Execute first arm
End
Check second pattern
Yes
Execute second arm
End
Check next patterns...
Default arm or error
The program checks each pattern in order. If the value matches any pattern in an arm, it runs that arm and stops matching.
Execution Sample
Rust
let x = 2;
match x {
  1 | 2 => println!("One or Two"),
  3 => println!("Three"),
  _ => println!("Other"),
}
This code matches x against multiple patterns in one arm using | to combine them.
Execution Table
StepValue of xPattern CheckedMatch ResultAction TakenOutput
121 | 2MatchExecute armOne or Two
223Not checkedNo action
32_Not checkedNo action
💡 Match found at first pattern (1 | 2), so matching stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x2222
Key Moments - 2 Insights
Why does the program not check the second pattern when the first matches?
Because Rust stops matching once it finds a matching pattern, as shown in execution_table step 1 where the first pattern matches and later patterns are not checked.
How do we match multiple values in one arm?
By using the | symbol between patterns, like 1 | 2, which means match if value is 1 or 2, as seen in execution_table step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 1?
A"One or Two"
B"Three"
C"Other"
DNo output
💡 Hint
Check the 'Output' column in execution_table row 1.
At which step does the program stop checking patterns?
AStep 3
BStep 2
CStep 1
DIt checks all steps
💡 Hint
See 'Match Result' and 'Action Taken' in execution_table; matching stops at first match.
If x was 3, which pattern would match according to the table?
A1 | 2
B3
C_
DNo pattern matches
💡 Hint
Look at the patterns and think which matches value 3.
Concept Snapshot
match value {
  pattern1 | pattern2 => action,
  pattern3 => action,
  _ => default_action,
}
- Use | to match multiple patterns in one arm.
- Matching stops at first successful pattern.
- _ matches anything else.
Full Transcript
This example shows how Rust matches a value against multiple patterns using the | symbol. The program checks each pattern in order. If the value matches any pattern in an arm, it runs that arm and stops matching further. For example, when x is 2, it matches the first arm with patterns 1 or 2, prints "One or Two", and stops. This prevents checking other patterns unnecessarily. Using | lets you combine multiple values in one match arm for cleaner code.