cmd/vet: obvious shadowing is not detected #21606
Comments
|
please be more specific :) what this idiom is useful for? |
Making the variable local to the loop body, primarily for closures:
|
That is mentioned in the last part of https://golang.org/doc/faq#closures_and_goroutines. |
is it any better than
|
You can accidentally use |
fair enough. so what do you think? |
When you iterate over some interface types that represent ADT-like values (see example below), you may want to introduce type-asserted version of it inside inner scope: // A.
for _, decl := range f.Decls {
decl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
// Use func decl.
}
// B: makes code more nested. Also does shadowing.
for _, decl := range f.Decls {
if decl, ok := decl.(*ast.FuncDecl); ok {
// Use func decl.
}
} At least for me, it feels consistent with type switch idiom where you do assignment to the variable of the same name: switch n := n.(type) {
case A:
// n is of type A.
case B:
// n is of type B
} |
@AlekSi how about this one?
|
cmd/vet/README lists the requirements for a vet check. There is plenty of code that shadows variables explicitly to make a local copy, and reuses the same name to ensure that it is impossible to refer to the outer "wrong" one anymore. (I'm just repeating the conversation above, with @dominikh and @onokonem). Rejecting "obvious" shadowing like this will generate far too many false positives, which makes people not trust vet output (even output from other checks). |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes it does
What operating system and processor architecture are you using (
go env
)?What did you do?
I run
go vet --shadow
for the following codeWhat did you expect to see?
Shadowing warning
What did you see instead?
No warnings
The text was updated successfully, but these errors were encountered: