Self Assignment

ID

go.self_assignment

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

CWE:480, reliability, suspicious-comparison

Description

Reports assignments whose left-hand side and assigned value are the same expression, for example x = x. The assignment is a no-op and almost always signals a copy-paste mistake or a wrong variable on one side. Go’s tuple assignments are reported only when every position assigns to itself (a, b = a, b) — swaps (a, b = b, a) and partial updates are never flagged.

Rationale

A statement like total = total does nothing, yet it reads as if it should. The most common real-world cause is a method that means to copy a parameter into a struct field but assigns the parameter to itself instead — leaving the field unchanged. Flagging the no-op surfaces the bug. Augmented assignments (+=, |=, …​) and short variable declarations (:=) are not reported.

type account struct {
    balance int
}

func (a *account) reset(balance int) {
    balance = balance   // FLAW — assigns the parameter to itself; the field stays unchanged
    a.balance = balance // OK — copies the parameter into the field
    a.balance += balance // OK — augmented assignment is not a no-op
}

Remediation

Decide which side was intended. If a struct field should receive a parameter, qualify it with the receiver (a.balance = balance). If the statement is genuinely redundant, delete it.