Search⌘ K
AI Features

Higher-Order Functions

Explore how to use higher-order functions in Go by treating functions as values and parameters. Understand how to implement callbacks and filters to manipulate slices based on custom boolean functions such as isOdd and isEven. This lesson helps you master practical usage of function types for flexible and reusable code.

Function used as a value

Functions can be used as values just like any other value in Go. In the following code, f1 is assigned a value, the function inc1:

func inc1(x int) int { return x+1 }
f1 := inc1 // f1 := func (x int) int { return x+1 }

Function used as a parameter

Functions can be used as parameters in another function. The passed function can then be called within the body of that function; that is why it is commonly called a callback. To illustrate, here is a simple example:

Go (1.6.2)
package main
import (
"fmt"
)
func main() {
callback(1, Add) // function passed as a parameter
}
func Add(a, b int) {
fmt.Printf("The sum of %d and %d is: %d\n", a, b, a + b)
}
func callback(y int, f func(int, int)) {
f(y, 2) // this becomes Add(1, 2)
}

To understand the code, look at line 10 at the function ...