《Mastering Concurrency in Go》书中的一段话让我觉得我可能遗漏了一些关于“defer”函数的内容。
您还应该注意通过引用传递的任何数据都可能处于意外状态。
func main() {
aValue := new(int)
defer fmt.Println(*aValue)
for i := 0; i < 100; i++ {
*aValue++
}
}
我想这会打印 0,因为根据规范:
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew
也就是说,调用 defer 时 *aValue 为 0,这就是为什么最后打印 0。在这种情况下,是否将指针传递给 diff 函数是无关紧要的。
我的理解正确还是我遗漏了什么?
最佳答案
考虑使用结构的情况。
type User struct {
Name string
}
func main() {
user := User{}
defer fmt.Printf("%#v\n", user)
user.Name = "AJ"
}
您知道 defer
应该在最后运行,因此您可能希望看到 User{Name: "AJ"}
但您得到的是 User{Name : ""}
因为 defer
绑定(bind)参数。
如果您使用指针,它就可以工作。
user := &User{}
如果你使用闭包,它就可以工作。
defer func() {
fmt.Printf("%#v\n", user)
}()
关于go - 通过引用 "defer"传递的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41471236/