go随聊-闭包

什么是闭包

        闭包就是一个匿名函数和一个外部变量(成员变量)组成的一个整体 ,通俗的讲就是一个匿名函数中引用了其外部函数内的一个变量而这个变量和这个匿名函数的组合就叫闭包。如下代码所示:

func inner() func() int {
	count:=0
	return func() int {
		count++
		return count
	}
}

inner函数中定义一个count变量,同时返回一个func

func Closure() {
	f1:=inner()
	a1:=f1()
	fmt.Println("f1:",a1)
	a2:=f1()
	fmt.Println("f1:",a2)
	a3:=f1()
	fmt.Println("f1:",a3)
}

Closure函数中调用inner函数,返回一个f1,然后多次调用f1() 会有什么结果呢 

f1: 1
f1: 2
f1: 3

在闭包中持有该变量的引用 而匿名函数所操作的变量一直是该闭包中的变量的引用,所以多次调用f1()函数操作的是同一个变量count,那么值逐渐增长也就不奇怪了。

如果多次调用inner获取闭包呢,会是什么情况

func Closure() {
	f1:=inner()
	a1:=f1()
	fmt.Println("f1:",a1)
	a2:=f1()
	fmt.Println("f1:",a2)
	a3:=f1()
	fmt.Println("f1:",a3)

	f2:=inner()
	a1=f2()
	fmt.Println("f2:",a1)
	a2=f2()
	fmt.Println("f2:",a2)
	a3=f2()
	fmt.Println("f2:",a3)
}
f1: 1
f1: 2
f1: 3
f2: 1
f2: 2
f2: 3

所以每个闭包中的引用变量count都是不同的

猜你喜欢

转载自blog.csdn.net/yimin_tank/article/details/83417515