0
0
Rustprogramming~10 mins

Match guards in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Match guards
Start with value
Match arm 1?
NoMatch arm 2?
Execute arm code
End
The program checks each match arm in order. If the pattern matches and the guard condition is true, it runs that arm's code. Otherwise, it moves to the next arm.
Execution Sample
Rust
let x = 5;
match x {
  n if n < 3 => "small",
  n if n < 7 => "medium",
  _ => "large",
}
Match the value x with conditions using guards to decide if it's small, medium, or large.
Execution Table
StepMatch Arm PatternGuard ConditionGuard ResultAction TakenOutput
1n if n < 35 < 3falseSkip arm
2n if n < 75 < 7trueExecute arm"medium"
3_N/AN/ANot reached
💡 Match arm 2 guard is true, so execution stops after returning "medium".
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x5555
nN/A555
Key Moments - 2 Insights
Why does the first match arm get skipped even though the pattern matches?
Because the guard condition (5 < 3) is false, the arm is skipped as shown in execution_table step 1.
What happens if no guard condition is true?
The default arm (_) runs, as a fallback. Here, it is not reached because step 2's guard is true.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the guard result at step 1?
Afalse
Btrue
CN/A
Derror
💡 Hint
Check the 'Guard Result' column in execution_table row 1.
At which step does the match stop and return a value?
AStep 3
BStep 1
CStep 2
DNever stops
💡 Hint
Look at the 'Action Taken' and 'Output' columns in execution_table.
If x was 2, which arm would execute?
AArm 3 (_)
BArm 1 (n if n < 3)
CArm 2 (n if n < 7)
DNo arm executes
💡 Hint
Check the guard conditions and their results for x=2 in the variable_tracker and execution_table logic.
Concept Snapshot
Match guards add extra conditions to match arms.
Syntax: pattern if condition => expression
The arm runs only if pattern matches AND condition is true.
If guard is false, matching continues to next arm.
Useful for fine control in pattern matching.
Full Transcript
This example shows how Rust's match guards work. The value x is matched against patterns with extra conditions called guards. Each arm has a pattern and a guard condition. The program checks each arm in order. If the pattern matches and the guard condition is true, it executes that arm's code and stops. Otherwise, it moves to the next arm. In the example, x=5 does not satisfy the first guard (5 < 3 is false), so it skips that arm. The second arm's guard (5 < 7) is true, so it runs that arm and returns "medium". The default arm is not reached. Variables x and n keep their values throughout. This helps control matching with extra checks beyond just the pattern.