认识闭包
首先来看一段代码:
1 package main
2
3 import (
4 "fmt"
5 )
6
7 func squares() func() int {
8 var x int
9 return func() int {
10 x++
11 return x * x
12 }
13 }
14
15 func main() {
16 f1 := squares()
17 f2 := squares()
18
19 fmt.Println("first call f1:", f1())
20 fmt.Println("second call f1:", f1())
21 fmt.Println("first call f2:", f2())
22 fmt.Println("second call f2:", f2())
23 }
调试结果是这样的:
代码很简单,就是定义一个square函数,返回值类型是func() int。