dsizmmwnm56437180 2017-01-04 18:53
浏览 13
已采纳

通过引用传递给“延期”的数据

There is a passage in the "Mastering Concurrency in Go" book which made me think I might be missing something about "defer" functions.

You should also take note that any data passed by reference may be in an unexpected state.

func main() {
    aValue := new(int)
    defer fmt.Println(*aValue)

    for i := 0; i < 100; i++ {
         *aValue++
    }
}

This prints 0, I thought, because according to spec:

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew

That is, *aValue is 0 when defer is called and that's why at the end it prints 0. Whether or not a pointer is passed to the differ function in this case is irrelevant.

Is my understanding correct or am I missing something?

  • 写回答

2条回答 默认 最新

  • douqiao3930 2017-01-04 20:35
    关注

    Consider a situation using structs.

    type User struct {
        Name string
    }
    
    func main() {
        user := User{}
        defer fmt.Printf("%#v
    ", user)
        user.Name = "AJ"
    }
    

    You know defer should run at the end, so you might expect to see User{Name: "AJ"} but instead you get User{Name: ""} because defer binds parameters.

    If you use a pointer it works.

        user := &User{}
    

    If you use a closure, it works.

        defer func() {
            fmt.Printf("%#v
    ", user)
        }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败