package main
import "fmt"
func a()(i int) {
defer func(){ fmt.Println("2:",i) }() defer fmt.Println("1:",i) i++ return }
func main() {
a() }
output:
1: 0
2: 1
匿名函数的 defer 为何是 1,是因为闭包函数共享了作用域的变量?

package main
import "fmt"
func a()(i int) {
defer func(){ fmt.Println("2:",i) }() defer fmt.Println("1:",i) i++ return }
func main() {
a() }
output:
1: 0
2: 1
匿名函数的 defer 为何是 1,是因为闭包函数共享了作用域的变量?
1 codehz Nov 18, 2019 via Android defer 时,(顶层)函数参数是立即求值的,然后匿名函数的话,自然就是用外面的 i 了 (这种技巧也可以用来统计函数运行时间 defer Count(time.Now()) |
2 ManjusakaL Nov 18, 2019 https://golang.org/ref/spec#Defer_statements 其实看下 spec 就明白了 > Each time a "defer" statment executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked |
3 BOYPT Nov 18, 2019 挺有意义的,比如 defer cancel()后面又有另外一个 xx, cancel := xxx,前面的 cancel 不会被覆盖 |
4 TypeErrorNone Nov 18, 2019 首先 i = 0 执行 defer fmt.Println("1:",i),这里是传参操作,把 i=0 传值进去了。 执行 defer func(){fmt.Println("2:",i)}时,i=1,所以输出 1 |
5 TypeErrorNone Nov 18, 2019 |