A Go function can be passed to other functions as a parameter. Such a function is called a higher-order function.
Go function as a parameter
In the example, the apply function takes the inc() and dec() functions as parameters.
package main
import "fmt"
func inc(x int) int {
x++
return x
}
func dec(x int) int {
x--
return x
}
func apply(x int, f func(int) int) int {
r := f(x)
return r
}
func main() {
r1 := apply(5, inc)
r2 := apply(4, dec)
fmt.Println(r1)
fmt.Println(r2)
}
Output:
6 3
Comments
Post a Comment