match whose arms only yield true and false
ID |
rust.maintainability.match_like_matches_macro |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Idiom |
Language |
Rust |
Description
Reports a match whose arms produce nothing but true and false, so the whole expression is a membership test written as control flow. The matches! macro expresses it in one line.
Rationale
Spelling a boolean test as a multi-arm match buries the question being asked in five or six lines of braces and fat arrows, and the reader has to check every arm to be sure which way the answer goes - a later edit that adds an arm returning true changes the meaning with nothing to signal it. matches! puts the pattern and the value side by side, so the test reads as the predicate it is.
The following code illustrates the pattern detected by this rule:
#[derive(Clone, Copy)]
pub enum Kind {
Alpha,
Beta,
Gamma,
}
pub fn is_alpha(k: Kind) -> bool {
// FLAGGED: match whose arms only yield true and false
match k {
Kind::Alpha => true,
_ => false,
}
}
Remediation
Rewrite with the macro - match k { Kind::Alpha ⇒ true, _ ⇒ false } becomes matches!(k, Kind::Alpha), several true arms become one | alternation (matches!(k, Kind::Alpha | Kind::Beta)), and the inverted form becomes !matches!(k, Kind::Alpha). Guards are supported: matches!(n, x if x > 0).