In this example, we will show you how to create a higher-order function in Go with an example.
A higher-order function is a function which either accepts a function as a parameter or returns a function.
Go higher-order function
In the example, we have some complex operations with functions. The apply function takes two functions as parameters. The getAddSub() function returns two functions.
package main
import "fmt"
func main() {
x := 8
y := 7
add, sub := getAddSub()
r1, r2 := apply(x, y, add, sub)
fmt.Printf("%d + %d = %d\n", x, y, r1)
fmt.Printf("%d - %d = %d\n", x, y, r2)
}
func apply(x, y int, add func(int, int) int, sub func(int, int) int) (int, int) {
r1 := add(x, y)
r2 := sub(x, y)
return r1, r2
}
func getAddSub() (func(int, int) int, func(int, int) int) {
add := func(x, y int) int {
return x + y
}
sub := func(x, y int) int {
return x - y
}
return add, sub
}
Output:
8 + 7 = 15 8 - 7 = 1