Function as value
The Go programming language provides flexibility to create functions dynamically and use their values. In the following example, we have defined variables with the initialization function. The purpose of this function variable is simply to use the built-in() function. Here is an example:
package main
import (
"fmt"
"math"
)
func main(){
/* declare a function variable */
getSquareRoot := func(x float64) float64 {
return (x)
}
/* use the function */
(getSquareRoot(9))
}
When the above code is compiled and executed, it produces the following results:
3
Function closure
The Go programming language supports anonymous functions that can be used as function closures. When we want to define a function inline without passing any name, it can use anonymous functions. In our example, we create 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 is 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 */
(nextNumber())
(nextNumber())
(nextNumber())
/* create a new sequence and see the result, i is 0 again*/
nextNumber1 := getSequence()
(nextNumber1())
(nextNumber1())
}
When the above code is compiled and executed, it produces the following results:
1 2 3 1 2