求解为啥defer输出的不是最终值?
```
package main
import "fmt"
func main() {
var i = new(int)
defer func(i *int) {
fmt.Println("3:", *i)
}(i)
defer fmt.Println("2:", *i)
*i++
fmt.Println("1:", *i)
}
//1: 1
//2: 0
//3: 1
```
我猜应该是和println接收的interface有关,但是不是很肯定和原因是什么?谢谢了。
更多评论
打印指针。
```
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