-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
What version of Go are you using (go version
)?
1.11 but NA
Does this issue reproduce with the latest release?
Sure.
What operating system and processor architecture are you using (go env
)?
Human brain, some kind of godawful biological monstrosity. "go env" apparently says "i'd like some pizza now".
What did you do?
Tried to explain defer statements to a reasonably competent programmer not familiar with go's spec enough to fully understand the semantics of named return variables.
https://golang.org/ref/spec#Defer_statements
https://play.golang.org/p/qwKgqdXIc4W
(note: I understand and expected this, I'm not saying the language's behavior is wrong)
What did you expect to see?
Slightly clearer spec.
What did you see instead?
The problem here is the spec's phrasing "deferred functions are invoked immediately before the surrounding function returns". Even knowing how it works, I read this as strongly suggesting that the fails() function should work, at least in the case where the return statement is hit; after all, the deferred function should happen immediately before the return.
In fact, deferred functions appear to happen roughly as the function returns. They are clearly after any return statements in the function itself, but they are clearly before stack unwinding. But if I had only the spec, and not experience with the language, I'd expect them to take place before the return, and thus, I'd expect a return foo
to end up yielding the value of foo as modified by a deferred function.
Suggested alternative: "immediately after function execution completes, but before returning control to the caller". The example does make the intent more clear, but it doesn't rule out the expectation that returning a named variable would work the same way.
Similarly, the example's "unlock happens before surrounding function returns" could be misleading. Say my return
statement uses the locked thing. Does the unlock happening "before" the return make that dangerous? No, but it sounds like it does.