Create higher-order functions in Go
Create higher-order functions in Go
A higher-order function takes a function value as an argument or returns one as a result. It can separate a reusable algorithm from a specific operation. A parameter such as func(int) int accepts a function with one int parameter and one int result.
package main
import ( "fmt")
func apply(x int, f func(int) int) int { return f(x) }func double(x int) int { return x * 2 }func main() { fmt.Println(apply(6, double)) fmt.Println(apply(6, func(x int) int { return x + 1 }))}apply invokes the supplied function, not a hard-coded operation. Pass double without parentheses to supply its function value. A function literal works too when its signature matches. Calling a nil function value panics; require a non-nil argument or explicitly handle nil.
Expected output:
127Transform a slice with a function
package main
import ( "fmt")
func transform(xs []int, f func(int) int) []int { out := make([]int, len(xs)) for i, x := range xs { out[i] = f(x) } return out}func main() { xs := []int{1, 2, 3} fmt.Println(transform(xs, func(x int) int { return x * x })) fmt.Println(xs)}The function allocates a separate output slice. It applies f once per element in order. With the pure squaring callback shown, the input stays unchanged; arbitrary callbacks can have side effects. For a small one-off loop, an extra abstraction may not be necessary.
Expected output:
[1 4 9][1 2 3]Try it locally
Implement applyTwice(x int,f func(int) int) int, which calls f on x and again on that result. Use an increment-by-2 function with x=3.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and closures 05: Create higher-order functions in Go
Check the lesson objective before moving on.
How do you pass a named function double as an argument?
What happens when a nil function value is called?