Boolean compared against a true or false literal
ID |
rust.maintainability.bool_comparison |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundant Code |
Language |
Rust |
Description
Reports an equality or inequality comparison between an expression and a true or false literal. The operand is already a bool, so the comparison reproduces the value it is testing.
Rationale
The comparison adds a step the reader has to evaluate mentally to recover the condition, and the two spellings are easy to confuse: x != false and x == false differ by one character and mean opposite things. Dropping the literal removes a whole class of typo.
The following code illustrates the pattern detected by this rule:
fn ready() -> bool {
true
}
pub fn checks(flag: bool, other: bool) -> i32 {
// FLAGGED: Boolean compared against a `true` or `false` literal
if flag == true {
return 1;
}
// FLAGGED: Boolean compared against a `true` or `false` literal
if flag != false {
return 2;
}
// FLAGGED: Boolean compared against a `true` or `false` literal
if false == other {
return 3;
}
// FLAGGED: Boolean compared against a `true` or `false` literal
if true != other {
return 4;
}
// FLAGGED: Boolean compared against a `true` or `false` literal
if ready() == false {
return 5;
}
0
}