func main() {
println(DeferFunc1(1))
println(DeferFunc2(1))
println(DeferFunc3(1))
}
func DeferFunc1(i int) (t int) {
t = i
defer func() {
t += 3
}()
return t
}
func DeferFunc2(i int) int {
t := i
defer func() {
t += 3
}()
return t
}
func DeferFunc3(i int) (t int) {
defer func() {
t += i
}()
return 2
}
Above code will print: 4 1 3
. Can anyone explain this? Of course, DeferFunc1
should return 4
. But why will DeferFunc2
and DeferFunc3
will return 1
and 3
respectively? Is that about closure or variable scope in Go?