I am reading through the go specification and don't fully understand the behavior of an example for defer.
// f returns 1
func f() (result int) {
defer func() {
result++
}()
return 0
}
The function has a named return, which an anonymous deferred function increments. The function ends with "return 0". This value is not returned, but the incremented variable instead.
In trying to understand this behavior, I've run into more questions. If I assign a value to the return variable, that seems to have no effect on the return value.
//b returns 1
func b() (result int) {
result = 10
defer func() {
result++
}()
return 0
}
However, if the last line is changed to:
return result
Things behave as I would expect.
https://play.golang.org/p/732GZ-cHPqU
Can someone help me better understand why these values get returned and the scope of these functions.