Self assignment¶
ID: go/redundant-assignmentKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctness - external/cwe/cwe-480 - external/cwe/cwe-561Query suites: - go-security-and-quality.qls
Click to see the query in the CodeQL repository
Assigning a variable to itself typically indicates a mistake such as a missing qualifier or a misspelled variable name.
Recommendation¶
Carefully inspect the assignment to check for misspellings or missing qualifiers.
Example¶
In the example below, the struct typeRect has two setter methodssetWidth andsetHeight that are meant to be used to update thewidth andheight fields, respectively:
packagemaintypeRectstruct{x,y,width,heightint}func(r*Rect)setWidth(widthint){r.width=width}func(r*Rect)setHeight(heightint){height=height}
Note, however, that insetHeight the programmer forgot to qualify the left-hand side of the assignment with the receiver variabler, so the method performs a useless assignment of thewidth parameter to itself and leaves thewidth field unchanged.
To fix this issue, insert a qualifier:
packagemainfunc(r*Rect)setHeightGood(heightint){r.height=height}
References¶
The Go Programming Language Specification:Assignments.
Common Weakness Enumeration:CWE-480.
Common Weakness Enumeration:CWE-561.