Go – function closure

  • Post author:
  • Post category:GO
  • Post comments:1 Comment
Go - function closure

This topic is about Go – function closure.

Go programming language supports anonymous functions which can acts as function closures. Anonymous functions are used when we want to define a function inline without passing any name to it.

In our example, we created a function getSequence() which returns another function. The purpose of this function is to close over a variable i of upper function to form a closure.

package main

import "fmt"

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

func main(){
   /* nextNumber is now a function with i as 0 */
   nextNumber := getSequence()  

   /* invoke nextNumber to increase i by 1 and return the same */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   
   /* create a new sequence and see the result, i is 0 again*/
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

When the above code is compiled and executed, it produces the following result −

1
2
3
1
2

To know more, Click Here.

This Post Has One Comment

Leave a Reply