New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
cmd/vet: warn about unused struct or array, ignoring assignment to field or element #449
Comments
Your first example is definitely too strict. You suggest disallowing: v := new(Point) v.x = 1 but what about v := NewPoint() v.x = 1 or v := OldPoint() // returns a reference shared with others v.x = 1 The used and not set rules do not treat "new" specially. "v" is being used to get to the field v.x in all these examples. In particular, when v is a pointer, for _, v = range arr { v.i = 1 } is a perfectly legitimate program. It is only when v is a struct (not a pointer) that this matters. It might be reasonable to treat v.i = 1, when v is not a pointer, only as a write to v, not a read. I thought the specific rule was in the spec but I can't find it at the moment. Labels changed: added languagechange. Owner changed to r...@golang.org. Status changed to Thinking. |
> v := OldPoint() // returns a reference shared with others > v.x = 1 Good point. My example is still logically incorrect I think, but not a compile error. Sorry. A revised example (as per your comment) for the record: var v struct{i int} v.i = 1 Interestingly, I think for _, v = range arr { v.i = 1 } illuminates a problem with adding generics to Go: the same code can have value or reference semantics depending on the underlying types. I guess that is what confused me, and as I said above, confuses new Go programmers. Thanks for considering the issue. |
To be clear, this is now only about:
The compiler reports that j is declared and not used, but it fails to report that both v and x are declared and not used. The spec says "Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used." I think that spec wording can be read as applying to all of j, v, and x, but it could break existing programs, hence the LanguageChange and Go2 tags. |
In the current Go ecosystem, this makes sense as a vet change. Let's repurpose this issue to adding this check to vet, rather than worrying about changing the compiler or language. |
by RyanneDolan:
The text was updated successfully, but these errors were encountered: