将参数传递给函数闭包 [英] Passing parameters to function closure
问题描述
我试图了解Go在创建带有参数的匿名函数与将该函数用作闭包之间的区别。这是一个差异示例。
I'm trying to understand the difference in Go between creating an anonymous function which takes a parameter, versus having that function act as a closure. Here is an example of the difference.
带有参数:
func main() {
done := make(chan bool, 1)
go func(c chan bool) {
time.Sleep(50 * time.Millisecond)
c <- true
}(done)
<-done
}
作为闭包:
func main() {
done := make(chan bool, 1)
go func() {
time.Sleep(50 * time.Millisecond)
done <- true
}()
<-done
}
我的问题是,第一种形式何时比第二种更好?您是否会为此类事情使用参数?我唯一看到第一种形式有用的是从另一个函数返回 func(x,y)
时。
My question is, when is the first form better than the second? Would you ever use a parameter for this kind of thing? The only time I can see the first form being useful is when returning a func(x, y)
from another function.
推荐答案
使用闭包与使用函数参数之间的区别与共享同一变量与获取值的副本有关。请考虑下面的两个示例。
The difference between using a closure vs using a function parameter has to do with sharing the same variable vs getting a copy of the value. Consider these two examples below.
在结束中,所有函数调用都将使用存储在 i $中的值c $ c>。在任何goroutine都没有时间打印其值之前,该值很可能已经达到3。
In the Closure all function calls will use the value stored in i
. This value will most likely already reach 3 before any of the goroutines has had time to print it's value.
在 Parameter 示例中,每个函数调用进行呼叫时,将通过 i
的值的副本,从而为我们提供我们更可能想要的结果:
In the Parameter example each function call will get passed a copy of the value of i
when the call was made, thus giving us the result we more likely wanted:
关闭时间:
for i := 0; i < 3; i++ {
go func() {
fmt.Println(i)
}()
}
结果:
3
3
3
3
3
3
参数:
for i := 0; i < 3; i++ {
go func(v int) {
fmt.Println(v)
}(i)
}
结果:
0
1
2
0
1
2
游乐场: http://play.golang.org/p/T5rHrIKrQv
这篇关于将参数传递给函数闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!