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.