Welcome To Golang By Example

Return a function from a function in Go (Golang)

In Golang function are first-order variables meaning that

While returning a function from another function, the exact signature of the function has to be specified return list. As in below example

func getAreaFunc() func(int, int)

Code:

package main

import "fmt"

func main() {
    areaF := getAreaFunc()
    res := areaF(2, 4)
    fmt.Println(res)
}

func getAreaFunc() func(int, int) int {
    return func(x, y int) int {
        return x * y
    }
}

Output:

8