Learn about functions as values and the use of function closures in the Go language

  • 2020-05-30 20:20:30
  • OfStack

Function as a value

The Go programming language provides the flexibility to dynamically create functions and use their values. In the following example, we have defined the variable with the initialization function. The purpose of this function variable is only to use the built-in Math.sqrt () function. Here's an example:


package main import (
   "fmt"
   "math"
) func main(){
   /* declare a function variable */
   getSquareRoot := func(x float64) float64 {
      return math.Sqrt(x)
   }    /* use the function */
   fmt.Println(getSquareRoot(9)) }

When the above code is compiled and executed, it produces the following results:


3

A function closure
The Go programming language supports anonymous functions that can be used as function closures. When we want to define a function that inlines without passing any name, it can use anonymous functions. In our example, we created a function getSequence() that will return another function. The purpose of this function is to close the variable i of the upper function to form a closure. Here's an example:


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 results:


1
2
3
1
2


Related articles: