匿名函数和闭包:匿名函数是无名称的函数,即时创建用于执行特定任务。闭包是在匿名函数中可以访问外部变量的变量。在 go 中,它们使用 func() 语法声明。匿名函数和闭包可用于传递参数、存储在变量中,或在实践中用于排序切片和事件处理。
Go 中的匿名函数和闭包
介绍
匿名函数是 Go 中没有显式命名并可以作为表达式的函数,它们 thường 用于创建一次性任务或回调。闭包是包含对外部变量的引用,即使函数返回后仍然存在的匿名函数。
匿名函数
使用 func()
语法声明匿名函数:
func() {
fmt.Println("这是一个匿名函数")
}
匿名函数可以作为参数传递给其他函数,也可以存储在变量中:
func callAnon(anon func()) {
anon()
}
var anonFunc = func() {
fmt.Println("这是一个存储在变量中的匿名函数")
}
闭包
闭包允许匿名函数访问外部作用域中的变量。这些变量被称为闭包变量。
var x = 10
anon := func() {
fmt.Println(x) // 访问闭包变量
}
anon() // 输出:10
实战案例
- 排序切片:使用闭包排序切片中按某个字段值:
type Employee struct {
Name string
Age int
}
func SortEmployeesByAge(employees []Employee) {
sort.Slice(employees, func(i, j int) bool {
return employees[i].Age < employees[j].Age
})
}
- 事件处理程序:创建接收器函数并指定匿名函数作为回调:
type Button struct {
onClick func()
}
func (b *Button) AddClickListener(f func()) {
b.onClick = f
}
开源项目和资源
- [Go wiki:Anonymous functions and Closures](https://go.dev/blog/closures)
- [Practical Go Tutorial: Closures](https://go.dev/blog/closures)
- [Golang 匿名函数和闭包](https://www.jianshu.com/p/8e78029d888a)