这是我的代码(
run):
- package main
- import "fmt"
- func main() {
- var whatever [5]struct{}
- for i := range whatever {
- fmt.Println(i)
- } // part 1
- for i := range whatever {
- defer func() { fmt.Println(i) }()
- } // part 2
- for i := range whatever {
- defer func(n int) { fmt.Println(n) }(i)
- } // part 3
- }
输出:
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’。因此
- 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’变量的值。因此
- 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’进行评估。