-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: cmd/vet: warn on defer as the last statement before return if the arguments exists prior to the penultimate statement to the return #64987
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
Comments
Falling through control flow should also be counted. if x {
r := Grab()
use(r)
defer r.Close()
}
return |
I'm afraid that this at the same time causes friction especially when writing tests and the tests get fleshed out step by step. In those cases govet will block running the test, even if it is fully correct.
|
@thediveo I tried covering this with:
It's very unclear (and incorrect). |
how frequent is this that it needs to be a vet check? |
How does this satisfy vet's 'Correctness' criteria? cmd/vet/README:
|
I don't understand this line. Do you mean whether or not arguments exist will affect the logic? (It certainly doesn't). |
I searched for matches in opensource code and there were a couple too much false positive, I thought it would be pretty rare, but yes this probably falls under styling. |
Proposal Details
I see regularly new comers using
defer
incorrectly.Some write things like this:
This code is tricky because it works, or at least looks to do so if you don't have a test for the failure case which also checks that
resource
is cleaned up properly.So I propose that
defer
s should be ago vet
error if they are the last statement before a return asis identical to
Unless one or more of their arguments (this include receivers, function arguments and variables captured by closures) are coming from the penultimate statement, this is so code like this remains ok:
Ideally this would be counted as per SSA rules so:
would remain ok, we could also replace this with more edge cases.
I see the acquire (+ if err != nil check) + defer close as it's own logical unit, and sometime you open a connection or file just to check that it is reachable or you have correct permissions, but then don't use it (yet).
However it tries to exclude acquire + use + defer close pattern which is a bug.
The text was updated successfully, but these errors were encountered: