Functions as Values

In Go, functions are “first-class citizens,” meaning they can be assigned to variables, passed as arguments, and returned from other functions.

Higher-Order Functions

A function that accepts another function as an argument is called a higher-order function.

func add(x, y int) int { return x + y }

func aggregate(a, b, c int, arithmetic func(int, int) int) int {
    result1 := arithmetic(a, b)
    return arithmetic(result1, c)
}

func main() {
    sum := aggregate(2, 3, 4, add) // sum is 9
}

Flexibility

This allows you to write highly generic logic. For example, a filter function could take any “criteria” function and apply it to a list, regardless of what the criteria actually are.