什么是一等函数
和其他类型有相同的地位,其他类型能用的地方函数一样能用,例如:
- 将函数赋值给变量
- 将函数传递给函数
- 创建并返回函数的函数
将函数赋值给变量
func a() int {
return 1
}
func b() int {
return 2
}
func main() {
c := a
fmt.Println(c()) //有点像别名?
c = b
fmt.Println(c()) //重新赋值时必须有相同的函数签名,即形参数量类型和返回值相同。
}
将函数传递给其他函数
func d(result func() int) {
e := result()
fmt.Println(e)
}
声明函数类型
闭包和匿名函数
闭包就是能够读取其他函数内部变量的函数。可以理解成定义在一个函数内部的函数。
包内的匿名函数:
package main
import "fmt"
var f = func() {
fmt.Println("hello,world")
}
func main() {
f() //调用匿名函数
}
函数内的匿名函数:
func main() {
f := func() {
fmt.Println("hello,world")
}
f()
}
声名和调用匿名函数整合在一起:
func main() {
func() {
fmt.Println("hello,world")
}
}