go - 通过引用 "defer"传递的数据

标签 go

《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/

相关文章:

go - Gorilla 工具包的无限重定向循环

go - 如何配置 go 命令以使用代理?

go - 如何从 Golang 中的结构访问特定字段

CSS 文件以 Content-Type : text/plain 发送

json:无法将数组解码为 main.Posts 类型的 Go 值

build - Go——没有可构建的 Go 源文件

go - 如何使用 gb 获得代码覆盖率?

json - 误解如何使用 MarshalJSON

templates - 如何使用文本/模板包评估字段?走

go - 使用 POST 请求 golang 上传文件