-
Notifications
You must be signed in to change notification settings - Fork 17.5k
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
x/blog: defer statements execute before/after the caller returns #45889
Comments
Is this a case that go vet could provide an error for? If a deferred function writes to a variable defined in the surrounding functions scope that has already returned, it seems to me like that is likely an error. |
The spec says
which is a more accurate representation of what's happening. this might not pass the accuracy bar for cmd/vet, ex #8220 |
I think we could reasonably tweak the blog entry to make it slightly more accurate (cc @adg since he wrote the blog post). |
Happy to review any amendments to the blog post. |
An individual vet check for this pattern seems to be an overkill for the reason mentioned in #8220. A more general check is to examine whether the writes within defer are used or not. In this example, b = 2 is not used (by the return) so this is suspicious. If b is a named return value then it is used by "return b". Of course the checker shall know about the correct control flow, e.g. "deferred functions are executed after any result parameters are set by that return statement but before the function returns to its caller".
This may be added as an extension of the "unusedwrite" checker. |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes.
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
In this example the defer function doesn't change the returned value whereas using the named return values would do the trick in this example.
If the defer function is executed after the caller returns as this blog post suggests, that would explain it. However, the doc says defer functions are executed before the caller returns.
What did you expect to see?
The blog post and the Golang doc being consistent.
What did you see instead?
The blog post says the list of saved calls is executed after the surrounding function returns whereas the Golang doc says the list of saved calls is executed before the surrounding function returns
The text was updated successfully, but these errors were encountered: