Skip to content
Latchkey

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.

go vet output
./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 block

Common 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.

Go
var err error
if v, err = f(); err != nil {   // = reuses the outer err
	return err
}
_ = v

Run the shadow analyzer in CI

shadow is not in the default vet set; install and run it explicitly.

.github/workflows/ci.yml
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 err in nested blocks.

Frequently asked questions

What causes ""declaration ... shadows""?
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.
How do I fix "declaration ... shadows"?
Use = (or declare the extra variable separately) so the outer variable receives the value.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card