Higher-order functions
We have already established that Go functions are values bound to a type. So, it should not be a surprise that a Go function can take another function as a parameter and also return a function as a result value. This describes the notion known as a higher-order function, which is a concept adopted from mathematics. While types such as struct
let programmers abstract data, higher-order functions provide a mechanism to encapsulate and abstract behaviors that can be composed together to form more complex behaviors.
To make this concept clearer, let us examine the following program, which uses a higher-order function, apply
, to do three things. It accepts a slice of integers and a function as parameters. It applies the specified function to each element in the slice. Lastly, the apply
function also returns a function as its result:
package main import "fmt" func apply(nums []int, f func(int) int) func() { for i, v := range nums { ...