0
0
Rustprogramming~5 mins

Match guards in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a match guard in Rust?
A match guard is an additional condition specified after a pattern in a match arm using if. It lets you add extra checks to decide if that arm should be chosen.
Click to reveal answer
beginner
How do you write a match guard in Rust?
You write a match guard by adding if condition after the pattern in a match arm. For example: Some(x) if x > 5 => ...
Click to reveal answer
intermediate
Why use match guards instead of just matching patterns?
Match guards let you check extra conditions that patterns alone can't express, like comparing values or calling functions, making your matching more precise.
Click to reveal answer
intermediate
What happens if multiple match arms match but only one has a true guard?
Rust chooses the first arm where the pattern matches and the guard condition is true. If the guard is false, Rust continues checking the next arms.
Click to reveal answer
intermediate
Can match guards use variables bound in the pattern?
Yes! Variables bound in the pattern can be used in the guard condition to make decisions based on their values.
Click to reveal answer
What keyword introduces a match guard in Rust?
Aif
Belse
Cmatch
Dguard
Which arm will be chosen in this code?<br>
match x {
  Some(n) if n > 10 => "big",
  Some(_) => "small",
  None => "none",
}
AThe first arm if n &gt; 10
BThe third arm if x is None
CBoth A and C depending on x
DThe second arm always
Can a match guard call functions?
AYes, any function can be called in a guard
BNo, only simple comparisons are allowed
COnly functions without parameters
DOnly functions returning booleans
What happens if a guard condition is false?
ARust restarts the match
BRust panics
CRust chooses that arm anyway
DRust skips that arm and checks the next
Can match guards be used with all pattern types?
ANo, only with enum variants
BYes, with any pattern
COnly with tuple patterns
DOnly with literals
Explain what a match guard is and how it changes pattern matching behavior in Rust.
Think about how you can add an extra check after matching a pattern.
You got /4 concepts.
    Describe a situation where using a match guard is better than just matching a pattern.
    Consider when you want to match a pattern only if a value meets a certain condition.
    You got /3 concepts.