doushuo1989 2017-12-28 05:00
浏览 69

go中的“ defer”是什么意思? [重复]

This question already has an answer here:

golang's documentation says this:

A deferred function's arguments are evaluated when the defer statement is evaluated.

This confuses me.

Question: Does "evaluated" mean that the value is already known? I just don't understand why two examples print different. This confuse me.

I have two examples below:

 //It prints 0.
 func deferA() {
     i := 0
     defer fmt.Println(i)
     i++
     return
 }

 //It prints 1.
 func deferB() {
      i := 0
      defer func() {
          fmt.Println(i)
      }()
      i++
      return
 }
</div>
  • 写回答

2条回答 默认 最新

  • duanhanzi8328 2017-12-28 05:06
    关注

    defer take a function, so fmt.Println(i) is a function and its argument i is evaluated as 0 when the defer statement is evaluated.

    defer func() { fmt.Println(i) }, the func() { fmt.Println(i) } take no argument and its a closure, so i is not evaluated but close over by the closure.

    You can more information about closure at https://gobyexample.com/closures

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料