Reputation: 101
I have some problem with using 'defer' about the return value. I tried to run one test function in different way (only the definition of i is different), but the result is different. So, I'm confused about the different return value. Here is the problem:
function 1:
package main
import "fmt"
func main() {
fmt.Println("a return:", a()) // return value: 0
}
func a() int {
var i int
defer func() {
i++
fmt.Println("a defer1:", i) // print " a defer1: 1"
}()
return i
}
return value:
a defer1: 1
a return: 0
function 2:
package main
import "fmt"
func main() {
fmt.Println("a return:", a()) // return value: 1
}
func a() (i int) {
defer func() {
i++
fmt.Println("a defer1:", i) // print " a defer1: 1"
}()
return i
}
return value:
a defer1: 1
a return: 1
One of the return values is 0, the other is 1. So, the question is what's the difference between the two function.
Upvotes: 8
Views: 2714
Reputation: 166598
what's the difference between the two functions?
The Go Programming Language Specification
A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns.
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.
if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes.
The difference is a surrounding function with a named result parameter
func a() (i int)
versus a surrounding function with an unnamed result parameter
func a() int
Upvotes: 8