Pattern match used only to test which variant an Option or Result holds
ID |
rust.maintainability.redundant_pattern_matching |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Idiom |
Language |
Rust |
Description
Reports a match, if let, while let or matches! over an Option or a Result that binds nothing and only asks which variant is present - the question is_some, is_none, is_ok and is_err answer directly.
Rationale
Destructuring machinery is being used for a question that is not about the contained value at all, which costs the reader a pattern to read and, in the match form, four lines of arms to confirm that both variants really do map onto the two booleans. The predicate methods say the same thing in one call, compose inside a larger condition, and cannot be got the wrong way round by a later edit that swaps two arm bodies.
The following code illustrates the pattern detected by this rule:
pub fn is_some_match(o: Option<i32>) -> bool {
// FLAGGED: Pattern match used only to test which variant an Option or Result holds
match o {
Some(_) => true,
None => false,
}
}
Remediation
Call the predicate - match o { Some() ⇒ true, None ⇒ false } becomes o.is_some(), if let Some() = o { … } becomes if o.is_some() { … }, matches!(r, Err()) becomes r.is_err(), and the negated forms become is_none / is_err. When the contained value is actually needed, keep the pattern and bind it instead of using .