Skip to content

proposal: cmd/vet: warn about cases where err is set but not used #71432

@ianlancetaylor

Description

@ianlancetaylor

Proposal Details

While working on an experimental tool for testing a new error handling syntax (https://go.dev/cl/643996), I came across three different instances of incorrect handling of err in Go code maintained by the Go team:

These cases all took the form

    // Some declaration and use of a variable named "err" of type "error",
    // followed by:
    err = F()
    // More code that does not look at "err".

In other words, the code was written to collect an error value, but the error value was never tested or used.

The Go compiler will warn about cases in which an err variable is set but never used, followed the spec implementation restriction "A compiler may make it illegal to declare a variable inside a function body if the variable is never used." However, in these cases the variable is in fact used. It's just not used after the final case in which it is set.

I think it would be difficult for us to tighten up that implementation restriction to say something like "A compiler may make it illegal to assign a value to a variable and then never use that variable again." I think that would likely break a lot of existing working Go code.

But I think that for the subset of cases in which a variable of type error is set and then never checked, it would be reasonable for vet to produce an error. Those cases are almost certainly mistakes. And even in the likely rare cases when they are not mistakes, the code would be clearer if it assigned to error result to _ rather than to err.

(I discovered these cases because there is no simple way to convert them to the proposed error handling syntax. Simple attempts to do produce a variable that is set and never used again, triggering the compiler error.)

CC @adonovan

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions