Golang: Function as Argument

By Xah Lee. Date: .

Function can be passed to another function as argument.

If a function is to take another function as argument, the tricky part is to specify the argument type, like this

func f(fname f_type_spec) return_type {body}

where the f_type_spec is this form:

func (param_spec) return_type2

Example:
func ff(gg func(int) int) int { return gg(1) }

package main

import "fmt"

func aa(n int) int {
	return n + 1
}

// ff takes a function arg
func ff(gg func(int) int) int {
	return gg(1)
}

func main() {

	fmt.Println(ff(aa)) // 2

}

golang function