Skip to content

cmd/compile: consistently report "declared but not used" errors - needs release notes #49214

@griesemer

Description

@griesemer

Problem

Per the spec:

A compiler may make it illegal to declare a variable inside a function body if the variable is never used.

a compiler may report errors for unused variables. The pre-1.18 compiler fails to do so if a variable is never used but set inside a function literal. Example:

package main
func main() {
        p := true
        func() {
                p = true
        }()
}

There is no use of p in this program but until now the compiler didn't report an error. See also issues #8560 and #46004.

The new 1.18 compiler front-end uses a go/types-based type checker (types2) which correctly reports an error in cases like these; so does go/types, and so does go/vet.

Proposal

The compiler should consistently report such errors from now on. This does not affect existing code that passes go/vet. There is a chance that code that used to compile (such as the example above) won't compile anymore; it is also likely that such code was not correct in the first place.

For existing code that won't compile anymore there are several work-arounds:

  1. Fix the code if it was in fact incorrect (this may be as simple as removing the unused variable, or using the correct variable).
  2. If the code was correct, address the error by introducing a use if the variable is still desired (which is as simple as _ = x for an unused variable x).
  3. Compile using the 1.17 compiler by setting the -G=0 compiler flag. This doesn't require code changes.

Implementation

If the proposal is accepted, nothing needs to be done; this is already the new behavior of the compiler.
If the proposal is not accepted, the compiler needs to be adjusted such that any access of a variable in a function literal is considered a "use".

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions