21.3 Refutable vs. Irrefutable Patterns
Rust distinguishes between:
- Refutable Patterns: These can fail to match. For example,
Some(x)
does not match a value ofNone
. Because they may fail, refutable patterns only appear in constructs that handle mismatches, such asmatch
arms orif let
. - Irrefutable Patterns: These always match. For instance,
let x = 5;
unconditionally binds5
tox
. Irrefutable patterns appear in places where a non-matching value would make the code invalid (for example,let
statements or function parameters).
If you need to account for possible mismatches (for instance, matching only the Some(x)
branch of an Option<T>
), you must use a refutable pattern within a match
, if let
, or another construct that can handle the alternative.