Latest web development tutorials

Go language function closures

Go language function closures

Go function Go function

Go language support anonymous functions can be used as closures. Anonymous function is an "inline" statement or expression. Superiority anonymous function that can use the variable within the function directly, without having to declare.

The following example, we create a function getSequence (), returns another function. The purpose of this function is increasing in a closure variable i, as follows:

package main

import "fmt"

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
     return i  
   }
}

func main(){
   /* nextNumber 为一个函数,函数 i 为 0 */
   nextNumber := getSequence()  

   /* 调用 nextNumber 函数,i 变量自增 1 并返回 */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   
   /* 创建新的函数 nextNumber1,并查看结果 */
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

The above code is executed as a result of:

1
2
3
1
2

Go function Go function