Reversed Compound Operator
ID |
go.reversed_compound_operator |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious-operator |
Description
Reports an assignment written as x =+ y, x =- y, x =^ y or x =! y, where the compound
operator was typed in reverse.
Go has no =+ operator. The statement parses as a plain assignment of a unary expression —
x = +y — so it overwrites x instead of accumulating into it. It compiles cleanly, and the
correct form differs from it by one space.
To keep the rule quiet on deliberate unary expressions, it fires only on the layout that reads as
an operator: the sign glued to the = and separated from its operand. x = +y and x =+y are
both left alone.
Rationale
The mistake is invisible in review because the two forms are one keystroke apart, and it is invisible in testing whenever the variable’s previous value happens to be the zero value — the overwrite and the accumulation then agree. The defect surfaces later, on the second iteration of a loop or the second call into a running service, as a total that is simply wrong.
x =! y is the same class of typo for the != comparison: written as a statement it assigns the
negation of y to x and discards the comparison the author meant to make.
func accumulate(total int, delta int) int {
total =+ delta // FLAW — assigns +delta; total += delta was meant
total =- delta // FLAW — assigns -delta; total -= delta was meant
return total
}
func toggle(flag bool, other bool) bool {
flag =! other // FLAW — assigns !other; flag != other was meant
return flag
}
Remediation
Use the compound operator, or restore the space if the unary expression was intended.
func accumulate(total int, delta int) int {
total += delta
total -= delta
return total
}
func negate(delta int) int {
return -delta // deliberate unary minus, spaced as such
}
Running gofmt on the file re-spaces the assignment to total = +delta, which makes the
remaining occurrences obvious.
and & are deliberately not covered: a leading or & on the right of an assignment is an
ordinary dereference or address-of in Go, not a typo signal.