Here are a few use cases:
1. Closures
Go has closures, meaning you can create an anonymous function which references enclosing variables. There are many great uses of closures, but this means that anonymous functions inherit their enclosing variable names.
err := trySomething()
workChan := make(chan work)
// start a worker
go func() {
// we're using the existing workChan from the enclosing scope
for job := range workChan {
// vv this is name shadowing! (we're shadowing the existing err)
err := do(job)
if err != nil {
logError(err)
}
}
}()
err = tryAnotherThing()
if err != nil {
return err
}
If we couldn't shadow the name, then the worker and the main thread would be competing for use of the same err
variable (resulting in undefined behaviour). So, you can thank shadowing for that you don't have to type err2
, errr
, etc.
2. Adding new names in enclosing scopes
Suppose you have an existing package and you want to add a new global constant or variable called gopher
. You don't want to have to search every scope in the the entire package source to see if the name gopher
was already used anywhere.
In the Go 1.18 release, there were added two new predeclared identifiers: any
and comparable
. Since name shadowing is allowed, universal identifiers like these can be added to Go without breaking previously correct Go programs (see also Go 1 compatability declaration)
3. Pasting code
Shadowing allows you to copy and paste "self contained" code like this, and have it work (pretty much) wherever you put it.
// Print Fibonacci numbers
for i, j := 0, 1; j < 100; i, j = j, i+j {
fmt.Println(j)
}
i
and j
are very common variable names so if shadowing isn't allowed, there's a good chance of conflict if you try to paste this somewhere in your code, resulting in an error.
Of course, it's generally good to avoid shadowing as it can lead to unexpected bugs and makes your code less readable (especially without scope-aware highlighting you might get in an IDE). In a longer, more realistic scenario, you would want to rename any shadowed names you might have pasted in. Thankfully, with shadowing being valid in the language, it should actually make it easier to rename them:
Since i
and j
are valid and distinct variables, a good IDE should allow you to quickly rename those variables and all their usages as you would any other variable.
i
variables in the question are declared in different blocks and have different scopes. Go does not allow the redeclaration of an identifier within a block.