golang 闭包
1.匿名函数的创建
a.fplus := func(x, y int) int { return x + y },然后通过变量名对函数进行调用:fplus(3,4)
b.直接对匿名函数进行调用:func(x, y int) int { return x + y } (3, 4)
下面是一个计算从 1 到 1 百万整数的总和的匿名函数:
func() {
sum := 0
for i := 1; i <= 1e6; i++ {
sum += i
}
}()
2.循环中最好不要使用匿名函数
下面的例子展示了如何将匿名函数赋值给变量并对其进行调用(function_literal.go):
package main
import "fmt"
func main() {
f()
}
func f() {
for i := 0; i < 4; i++ {
g := func(i int) { fmt.Printf("%d ", i) } //此例子中只是为了演示匿名函数可分配不同的内存地址,在现实开发中,不应该把该部分信息放置到循环中。
g(i)
fmt.Printf(" - g is of type %T and has value %v\n", g, g)
}
}
输出:
0 - g is of type func(int) and has value 0x681a80
1 - g is of type func(int) and has value 0x681b00
2 - g is of type func(int) and has value 0x681ac0
3 - g is of type func(int) and has value 0x681400
我们可以看到变量 g 代表的是 func(int),变量的值是一个内存地址。
所以我们实际上拥有的是一个函数值:匿名函数可以被赋值给变量并作为值使用。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: