Go/函数/匿名函数-闭包

## 匿名函数作为一个闭包,闭包以引用传递的方式捕获外部变量

package main

import "fmt"

func test(){
	a := 22
	str := "go"

	//匿名函数,闭包 以引用传递方式捕获外部变量
	func(){
		a = 23
		str = "gogo"
		fmt.Println(a,str)
	}() //直接调用匿名函数

	fmt.Println(a,str)
}

func main() {
	a := 33

	//定义匿名函数
	f1 := func(){
		fmt.Printf("访问匿名函数作用域之外的变量//闭包//,a=%d \n",a);
	}
	f1() //调用匿名函数

	type FuncType func ()
	var f2 FuncType = f1
	f2()

	//定义并直接调用匿名函数
	func(){
		fmt.Printf("访问匿名函数作用域之外的变量//闭包//,a=%d \n",a);
	}()

	x,y := func (i,j int) (c,d int){
		c = i+a
		d = j+a
		return
	}(1,2)
	fmt.Println(x,y)

	test()
}

##  闭包可以作为函数返回值  闭包离开作用域,其捕获的外部变量才会销毁

package main

import "fmt"

//返回值为匿名函数
func test() func () int {
	var i int 			//默认值0
	return func() int{
		i++
		return i*i
	}
}

func main() {
	f := test()			//f为一个匿名函数
	fmt.Println(f())	        //1*1
	fmt.Println(f())	        //2*2
	fmt.Println(f())	        //3*3
	//只有闭包f离开作用域main,其捕获的变量i才会销毁
}

猜你喜欢

转载自blog.csdn.net/qq_24243483/article/details/84038232