0
0
Rustprogramming~10 mins

Match overview in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Match overview
Start: Have a value
Match value against patterns
Check pattern 1
NoCheck pattern 2
Execute code block
End
The match expression checks a value against multiple patterns one by one and runs the code for the first matching pattern.
Execution Sample
Rust
let number = 2;
match number {
    1 => println!("One"),
    2 => println!("Two"),
    _ => println!("Other"),
}
This code matches the variable 'number' against patterns 1, 2, and a default, printing the matching case.
Execution Table
StepMatched ValuePattern CheckedMatch ResultAction TakenOutput
121NoCheck next pattern
222YesExecute println!("Two")Two
32_ (default)SkippedNo action
42EndMatch found, exitStop matching
💡 Match found at pattern 2, so matching stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
number2222
Key Moments - 2 Insights
Why does the match stop checking after finding the first match?
Because Rust's match expression runs only the first matching pattern's code and then exits, as shown in execution_table step 4.
What does the underscore (_) pattern mean in a match?
It means 'any other value' and acts as a default case if no previous patterns match, as seen in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what pattern matches the value 2?
APattern 1
BDefault (_) pattern
CPattern 2
DNo pattern matches
💡 Hint
Check the 'Match Result' column in execution_table row 2.
At which step does the match expression stop checking patterns?
AStep 4
BStep 2
CStep 1
DStep 3
💡 Hint
Look at the 'Action Taken' and 'Match Result' columns in execution_table step 4.
If number was 5, which pattern would match?
APattern 2
BDefault (_) pattern
CPattern 1
DNo pattern matches
💡 Hint
The default pattern matches any value not matched before, as explained in key_moments.
Concept Snapshot
match value {
    pattern1 => action1,
    pattern2 => action2,
    _ => default_action,
}

- Checks patterns top to bottom
- Runs first matching action
- '_' is default catch-all
- Stops after first match
Full Transcript
The Rust match expression compares a value against multiple patterns in order. It starts with the first pattern and checks if the value fits. If it does, it runs the code for that pattern and stops checking further. If not, it moves to the next pattern. The underscore (_) pattern is a default that matches anything not matched before. This way, match expressions let you run different code depending on the value, similar to a switch-case but more powerful and safe.