defer和fmt.Println

tyonc · · 737 次点击
延迟的是函数执行,defer声明时参数就计算确定了
#4
更多评论
打印指针。 ``` func main() { var i = new(int) defer func(i *int) { fmt.Printf("3:%p,%v\n", i, *i) }(i) defer fmt.Printf("2:%p,%v\n", i, *i) *i++ fmt.Printf("1:%p,%v\n", i, *i) } //1:0x1400001c0a0,1 //2:0x1400001c0a0,0 //3:0x1400001c0a0,1 ```
#1
defer 栈结构, 3闭包 ,2.不是很清楚,做了自己个断点看看源码吧。 有没有大佬来解? func main() { var i = new(int) *i = 5 defer func(i *int) { fmt.Printf("3:%p,%v\n", i, *i) }(i) *i = 500 defer fmt.Printf("2:%p,%v\n", i, *i) *i = 50 /*defer func() { //fmt.Println(i, *i) fmt.Printf("2:%p,%v\n", i, *i) }()*/ *i++ fmt.Printf("1:%p,%v\n", i, *i) }
#2