Go vet shadow - Fix Variable Shadowing Findings in CI
The shadow analyzer (run via go vet -vettool with the shadow tool) flags an inner declaration that hides an outer variable of the same name. The classic case is a := redeclaring err in an inner scope, so the outer err never sees the assignment.
What this error means
A vet shadow step fails with declaration of "err" shadows declaration at ..., pointing at an inner :=. The code compiles, but the shadowed variable means a value assigned inside the inner scope is silently dropped outside it.
./handler.go:18:3: declaration of "err" shadows declaration at line 14
# inner: if v, err := f(); ... { } // this err shadows the outer one
# outer err stays nil after the blockCommon causes
An inner := redeclares an outer variable
Using := inside an if/for block for a name that already exists outside creates a new inner variable. Assignments to it do not affect the outer one, which is usually a bug.
A shadowed err hiding a real error
The most common case: an inner := shadows err, so error handling after the block checks the outer (still nil) err and misses the failure.
How to fix it
Assign to the outer variable instead of redeclaring
Use = (or declare the extra variable separately) so the outer variable receives the value.
var err error
if v, err = f(); err != nil { // = reuses the outer err
return err
}
_ = vRun the shadow analyzer in CI
shadow is not in the default vet set; install and run it explicitly.
go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest
go vet -vettool=$(which shadow) ./...How to prevent it
- Reuse outer variables with
=rather than redeclaring with:=in inner scopes. - Run the shadow analyzer in CI for error-prone code.
- Watch especially for shadowed
errin nested blocks.