golang如何“推迟”捕获关闭参数?

前端之家收集整理的这篇文章主要介绍了golang如何“推迟”捕获关闭参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码( run):
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6. var whatever [5]struct{}
  7.  
  8. for i := range whatever {
  9. fmt.Println(i)
  10. } // part 1
  11.  
  12. for i := range whatever {
  13. defer func() { fmt.Println(i) }()
  14. } // part 2
  15.  
  16. for i := range whatever {
  17. defer func(n int) { fmt.Println(n) }(i)
  18. } // part 3
  19. }

输出

0
1
2
3
4
4
3
2
1
0
4
4
4
4
4

问题:第2部分和第2部分有什么区别?第3部分为什么第2部分输出“44444”而不是“43210”?

“第2部分”闭包捕获变量“i”。当闭包(稍后)中的代码执行时,变量“i”具有在范围语句的最后一次迭代中具有的值,即。 ‘4’。因此
  1. 4 4 4 4 4

输出的一部分。

“第3部分”没有捕获其关闭中的任何外部变量。正如specs所说:

Each time the “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.

所以每个被称为的函数调用都具有不同的’n’参数值。在执行延迟语句的时刻,它是’i’变量的值。因此

  1. 4 3 2 1 0

部分输出因为:

… deferred calls are executed in LIFO order immediately before the surrounding function returns …

要注意的一点是,当defer语句执行时,’defer f()’中的’f()’不执行

在延迟语句执行时,会对’defer f(e)’中的表达式’e’进行评估。

猜你在找的Go相关文章