Hello—
I’m getting started with Go, and I found something really odd with the defer
statement. (See code snippet below.)
In a nutshell: are named result parameters modified in a defer’d function
literal supposed to _completely override_ the existing return statement; that
is, even if a literal, and not the named result, is being returned?
Consider the following complete Go program:
-8<-
package main
import (
"fmt"
)
func main() {
fmt.Printf("Value returned is: %d\n", testDefer())
}
func testDefer() (value int) {
defer func() {
value = 2
}()
value = 1
return 3
}
->8-
I would expect testDefer() to return 3, because there’s no bare return, and a
literal 3, not “value”, is returned. However, it returns 2.
% go version
go version go1.2.1 darwin/amd64
% go run defer.go
Value returned is: 2
The language spec briefly mentions the interaction of defer and named result
parameters [1], but is silent on the above. Is this intended behavior?
Thanks.
[1] “For instance, if the deferred function is a function literal and the
surrounding function has named result parameters that are in scope within
theliteral, the deferred function may access and modify the result
parameters before they are returned.”
—
http://golang.org/ref/spec#Defer_statements