golang函数二(匿名函数和闭包)

  

匿名函数就是没有定义函数名称的函数。我们可以在函数内部定义匿名函数,也叫函数嵌套。

匿名函数可以直接被调用,也可以赋值给变量,作为参数或返回值比。如:

func 主要(){   ,,,func (s 字符串){,,,,//直接被调用   ,,,,,,,println (s)   ,,,}(hello 小田鼠! ! !)   ,,/*   ,,,func (s 字符串){,,,,//未被调用   ,,,,,,,println (s)   ,,,}   ,,*/}      func  main () {   ,,,hi :=, func (s 字符串){,,//赋值给变量   ,,,,,,,println (s)   ,,,}   ,,,,嗨(hello 小田鼠! ! !)   }         func 测试(f  func (string)) {   ,,,f (hello 小田鼠! ! !)   }   func  main () {   ,,,hi :=, func (s 字符串){   ,,,,,,,println (s)   ,,,}   ,,,测试(你好),,,,,//作为参数   }      func 测试()函数(字符串){   ,,,hi :=, func (s 字符串){,,//作为返回值   ,,,,,,,println (s)   ,,,}   ,,,return ,你好   }      func  main () {   ,,,f :=,测试()   ,,,f (hello 小田鼠! ! !)   }

普通函数和匿名函数都可以作为结构体的字段,比如:

{   ,,,type  calc 结构{   ,,,,,,,mul  func (x, y  int) int   ,,,}   ,,,x :=, calc {   ,,,,,,,mul:, func (x, y  int) int {   ,,,,,,,,,,,return  (x * y)   ,,,,,,,},   ,,,}   ,,,println (x.mul (2、3)   }

也可以经通道(通道)传递,比如:

{   ,,,c :=, (chan  func (int, int) int, 2)   ,,,c  & lt;作用;func (x, y  int), int  {return  x  +, y}   ,,,println ((& lt; - c) (2、3)   }

func  intSeq()函数(int) {   ,,,小姐::=0   ,,,println(和我)   ,,,return  func int () {   ,,,,,,,小姐:+=1   ,,,,,,,println(和我)   ,,,,,,return 我   ,,,},,,   }   ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,   func  main () {   ,,,nextInt :=, intSeq ()   ,,,fmt.Println (nextInt ())   ,,,fmt.Println (nextInt ())   ,,,fmt.Println (nextInt ())      ,,,newInt :=, intSeq ()   ,,,fmt.Println (newInt ())   }   输出:   0 xc42000a320   0 xc42000a320  1   1   0 xc42000a320  2   2   0 xc42000a320  3   3.   0 xc42007a010   0 xc42007a010  1   1

当nextInt函数返回后,通过输出指针,我们可以看出函数在主要运行时,依然引用的是原环境变量指针,这种现象称作闭包,所以说,闭包是函数和引用环境变量的组合体。

因为闭包是通过指针引用环境变量,那么就会导致该变量的生命周期

变长,甚至被分配到堆内存。如果多个匿名函数引用同一个环境变量,会让事情变得更加复杂,比如:

func 测试()[]func () {   ,,,var  s  [] func ()   ,,,for 我:=,0;小姐:& lt;, 3,我+ + {   ,,,,,,,s =,,附加(年代,func () {   ,,,,,,,,,,,println(和小姐:,,我)   ,,,,,,,})   ,,,}   ,,,return  s   }   func  main () {   ,,,funcSlice :=,测试()   ,,,for  _ ,, f :=, range  funcSlice {   ,,,,,,,f ()   ,,,}   }   输出:   0 xc42000a320  3   null   null   null   null   null   null   null   null   null   null   null

golang函数二(匿名函数和闭包)