go defer的坑

package mainimport ( "errors" "fmt" "runtime" )func main() { var err error err = nil var i int64 i = 0 defer dead(err, i) defer dead2(&err, &i) defer func() { // 闭包,err,i的值会随着调用函数的语句改变 _, _, line, _ := runtime.Caller(0) fmt.Printf("%v err:%vi:%v\n", line, err, i) }() defer func(err error, i int64) { // 虽然是闭包,但是 defer内函数的值拷贝 _, _, line, _ := runtime.Caller(0) fmt.Printf("%v err:%vi:%v\n", line, err, i) }(err, i)i = 5 err = errors.New("aaa")_, _, line, _ := runtime.Caller(0) fmt.Printf("%v err:%vi:%v\n", line, err, i) }func dead(err error, i int64) { // 值传递,defer声明的时候,error,i值已经确定了 _, _, line, _ := runtime.Caller(0) fmt.Printf("%v err:%vi:%v\n", line, err, i) }func dead2(err *error, i *int64) { // 指针传递,err i 指向的内容,会反映出defer执行时的内容。 _, _, line, _ := runtime.Caller(0) fmt.Printf("%v err:%vi:%v\n", line, *err, *i) }

    推荐阅读