Search⌘ K
AI Features

Functions That Return Other Functions

Explore how Go functions can return other functions to create dynamic and flexible code. Understand anonymous functions, closures, and how these concepts bring functional programming features to Go.

We'll cover the following...

Apart from accepting functions as arguments, functions can also return anonymous functions, which can be handy when the returned function is not always the same but depends on the function's input or other external parameters.

Coding example

This is illustrated in returnFunction.go:

Go (1.18.2)
package main
import "fmt"
func funRet(i int) func(int) int {
if i < 0 {
return func(k int) int {
k = -k
return k + k
}
}
return func(k int) int {
return k * k
}
}

The signature of funRet() declares that the function returns another function with the ...