Golang: Function Return Function

By Xah Lee. Date: .

To have a function return a function, the tricky part is in the return type spec.

func f() return_type {body}

The return_type must be a function type, like this:

func () return_type2

The whole thing looks like this:

func f() func () return_type2 {body}

package main

import "fmt"

// ff returns a function gg
func ff(x int) func(int) int {
	var gg = func(y int) int { return y + x }
	return gg
}

func main() {
	fmt.Println(ff(1)(2)) // 3

}

golang function