闭包(closure)
一个外层函数中有内层函数,该内层函数中操作了外层函数的局部变量(外层函数的参数或直接定义的变量),并且该外层函数的返回值就是这个内层函数,则内层函数和外层函数的局部变量统称为闭包结构。
该局部变量的生命周期会发生改变,正常局部变量的生命周期随着函数的调用而创建,随着调用的结束和销毁。但闭包中外层函数的局部变量并不会随着外层函数的调用结束而销毁,因为内层函数有可能会继续使用该局部变量。
package main
import (
"fmt"
)
func main() {
fun1 := increment()
fmt.Printf("type: %T\n", fun1) // type: func() int
fmt.Printf("value: %v\n", fun1) // value: 0x1021e1590
fmt.Println("fun1: ", fun1()) // 1
fmt.Println("fun1: ", fun1()) // 2
fun2 := increment()
fmt.Println("fun2: ", fun2()) // 1
fmt.Println("fun2: ", fun2()) // 2
fmt.Println("fun1: ", fun1()) // 3
}
func increment() func() int {
a, b := 0, 0
fun := func() int {
a++
fmt.Println("b:", b) // 一直是0
return a
}
return fun
}