Shadowing Variable
ID |
go.shadowing_variable |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports an inner := or var declaration that re-declares a name already in scope from an
enclosing scope of the same function.
Rationale
The inner binding hides the outer variable for the rest of the inner block, so assignments meant
for the outer variable silently affect only the inner copy. This is a classic, hard-to-spot Go
bug — especially with err, where a shadowed err := inside a block leaves the outer err
unchanged and an error goes unhandled.
x := 1
if x > 0 {
x := 2 // FLAW — inner x shadows outer x
_ = x
}
a := 1
if a > 0 {
b := 2 // OK — different name
_ = b
}
Remediation
Rename the inner variable, or assign to the existing outer variable with = instead of declaring
a new one with :=.