dongying9756
dongying9756
2014-07-13 06:20

Golang延迟行为

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

Effective Go states the following regarding defer:

The arguments to the deferred function (which include the receiver if the function is a method) are evaluated when the defer executes, not when the call executes. Besides avoiding worries about variables changing values as the function executes, this means that a single deferred call site can defer multiple function executions. Here's a silly example.

for i := 0; i < 5; i++ {
    defer fmt.Printf("%d ", i)
}

Deferred functions are executed in LIFO order, so this code will cause 4 3 2 1 0 to be printed when the function returns.

This example confuses me. If parameters are evaluated when the defer call is executed, then the defers in the for loop should print 5 5 5 5 5 since the defers will be called when the for loop ends, and at that time i would be 5. Evaluating defers at the end of the for loop will thus result in 5 for all calls.

Am I missing something here?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐

  • Golang延迟行为
    • it技术
    • 互联网问答
    • IT行业问题
    • 计算机技术
    • 编程语言问答
    • 3个回答