0
0
Rustprogramming~10 mins

Basic match usage in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Basic match usage
Start with a value
match value with patterns
Pattern 1?
YesExecute code 1
Pattern 2?
YesExecute code 2
Pattern 3?
YesExecute code 3
Default pattern
Execute default code
End match
The match expression compares a value against 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 checks the value of 'number' and prints a message depending on which pattern matches.
Execution Table
StepValue matchedPattern checkedMatch?Action executedOutput
121NoNone
222Yesprintln!("Two")Two
3-Default (_)SkippedNone
💡 Match stops after the first successful pattern match (pattern 2).
Variable Tracker
VariableStartAfter match
number22
Key Moments - 2 Insights
Why does the match stop after checking pattern 2 and not continue to the default?
Because match stops at the first pattern that matches the value, as shown in execution_table row 2 where pattern 2 matches and the default is skipped.
What does the underscore (_) pattern mean in the match?
The underscore is a catch-all pattern that matches any value not matched by previous patterns, as seen in execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what pattern is checked first?
APattern 1
BPattern 2
CDefault (_)
DPattern 3
💡 Hint
Check the 'Pattern checked' column in the first row of the execution_table.
At which step does the match find a successful pattern?
AStep 1
BStep 3
CStep 2
DNo successful match
💡 Hint
Look at the 'Match?' column to find where it says 'Yes'.
If 'number' was 5, which pattern would match?
APattern 1
BDefault (_)
CPattern 2
DNo pattern matches
💡 Hint
Refer to variable_tracker and the meaning of the underscore pattern in key_moments.
Concept Snapshot
match value {
    pattern1 => action1,
    pattern2 => action2,
    _ => default_action,
}

- Checks patterns top to bottom
- Runs code for first match
- '_' is catch-all default
- Stops after first match
Full Transcript
This example shows how Rust's match expression works. We start with a value 'number' set to 2. The match checks each pattern in order: first 1, then 2, then the default underscore. It finds that 2 matches pattern 2, so it runs the code to print "Two" and stops checking further patterns. The underscore pattern is a catch-all for any value not matched earlier. Variables keep their values unchanged during matching. This step-by-step trace helps understand how match chooses which code to run.