doutiao2540 2017-11-16 03:19
浏览 33

直接延迟调用函数和匿名函数调用之间的区别?

I got some code like this.

import (
  "fmt"
)

func ShowResult(result []string) {
  fmt.Println(result)
}

func main() {
  result := []string{}
  defer func() {
    ShowResult(result)
  }()
  defer ShowResult(result)
  result = append(result, "test")
}

And the result is:

[]
[test]

So could anyone tell me what is difference between calling a function directly and calling it in an anonymous function when defer?

  • 写回答

1条回答 默认 最新

  • dou448172583 2017-11-16 03:24
    关注

    The function arguments are evaluated when it is deferred. From the documentation

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

    When your deferred function is a closure, the ShowResult arguments are not evaluated until the closure is executed, which is immediately after the outer function returns and after the result value has been modified.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度