Go语言支持匿名函数,可以形成闭包。匿名函数在想要定义函数而不必命名时非常有用。
函数getSequence()
返回另一个函数,它在getSequence()
函数的主体中匿名定义。返回的函数闭合变量i
以形成闭包。
当调用intSeq()
函数,将结果(一个函数)分配给nextInt
。这个函数捕获它自己的i
值,每当调用nextInt
时,它的i
值将被更新。
通过调用nextInt
几次来查看闭包的效果。
func TestBB(t *testing.T) { /* nextNumber 为一个函数,函数 i 为 0 */ nextNumber := getSequence() /* 调用 nextNumber 函数,i 变量自增 1 并返回 */ fmt.Println(nextNumber()) fmt.Println(nextNumber()) fmt.Println(nextNumber()) /* 创建新的函数 nextNumber1,并查看结果 */ nextNumber1 := getSequence() fmt.Println(nextNumber1()) fmt.Println(nextNumber1()) } type cba func() int func getSequence() cba { i := 0 return func() int { i += 1 return i } }
代码地址:https://github.com/yangliuzzu/GO-daily-Study.git
ch9 文件夹下的 Hs_test.go