在函数定义中使用本地变量

huangapple go评论107阅读模式
英文:

Using local values in function definitions

问题

以下是要翻译的内容:

以下程序产生输出结果为 5, 5, 5, 5, 5。取消注释后,程序产生输出结果为 0, 1, 2, 3, 4。

是否有更好的(或者更符合惯用法的)方法,在函数声明中传递当前值,而不是使用 i := i

英文:

The following program

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type TestFunc func()
  6. func main() {
  7. fmt.Println()
  8. funcs := []TestFunc{}
  9. for i:=0; i<5; i++ {
  10. //i := i
  11. funcs = append(funcs, func() {fmt.Println(i)})
  12. }
  13. for _, f := range funcs {
  14. f()
  15. }
  16. }

produces an output 5, 5, 5, 5, 5. After uncommenting the line, the program

  1. for i:=0; i<5; i++ {
  2. i := i
  3. funcs = append(funcs, func() {fmt.Println(i)})
  4. }
  5. for _, f := range funcs {
  6. f()
  7. }

produces an output 0, 1, 2, 3, 4.

Is there a better (or an idiomatic) way to pass the current value to a function declaration instead of using i := i?

答案1

得分: 1

这是惯用的做法。

如果你立即调用函数,你也可以将它作为参数传递。

英文:

That is the idiomatic way of doing it.

You also could pass it as an argument, if you were calling the function immediately.

huangapple
  • 本文由 发表于 2014年9月18日 23:03:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/25916231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定