- named function can be declared only at the package level。命名函数只能在包级别声明!!!
- function literal:written like a function declaration, but without a name following the func keyword
类似于其他类型的字面量,匿名函数也是一个表达式,他的值叫做匿名函数
string.Map(func(r rune) rune { return r + 1 }, "HAL-9000")
重要:匿名函数可以使用局部环境中的变量的值。闭包!!!
func squares() func() int {
var x int
return func() int {
x++
return x * x
}
}
func main() {
f := squares()
fmt.Println(f()) //1
fmt.Println(f()) //4
fmt.Println(f()) //6
fmt.Println(f()) //9
}
- squares返回一个函数,这个函数在每次调用的时候都返回下一个数的平方数
- function valus are not just code but have state。函数类型的值不仅是操作顺序的集合,同时还可以持有状态
- function values 被定义为一种引用类型