Use bytes.Equal Instead Of bytes.Compare
ID |
go.bytes_compare_equal |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Go |
Tags |
code-style |
Description
Reports bytes.Compare(a, b) == 0 and bytes.Compare(a, b) != 0. When only equality matters,
bytes.Equal(a, b) says so directly.
Rationale
bytes.Compare performs a full three-way ordering comparison (-1/0/1). Using it just to
ask whether two slices are equal does more work than needed and reads less clearly than
bytes.Equal, which is also optimised for the equality case. Relational comparisons against 0
(< 0, > 0) are genuine ordering tests and are not reported.
// Bad
if bytes.Compare(a, b) == 0 {
handle()
}
// Good
if bytes.Equal(a, b) {
handle()
}
Remediation
Replace bytes.Compare(a, b) == 0 with bytes.Equal(a, b), and bytes.Compare(a, b) != 0 with
!bytes.Equal(a, b).