Anonymous functions in Go
As mentioned in the Golang dev blog [1], "programmers new to Go are often surprised by its support for function types, functions as values, and closures." Functions are first class in Go. Go supports a "functional programming style in a strongly typed language" [2]. We can use anonymous functions to form a closure that can be used directly. Here is an example of anonymous function used as a closure.
// go run closure.go
package main
import "fmt"
import "math"
func power(x int) func(int) int {
return func(y int) int{
return int(math.Pow(float64(x), float64(y)))
}
}
func main(){
var pow2 = power(2)
fmt.Printf("2 ^ 5 = %d\n", pow2(5))
var pow3 = power(3)
fmt.Printf("3 ^4 = %d\n", pow3(4))
}
You should see the following result:
2 ^ 5 = 32
3 ^4 = 81
We create an anonymous function inside power function, which generates power function with certain base. Then we use the generated function to calculate different powers.
[1] https://blog.golang.org/first-class-functions-in-go-and-new-go