Welcome To Golang By Example

Pass function as an argument to another function in Go (Golang)

Golang function are first-order variables meaning that

In GO function is also a type. Two functions are of the same type if they have the same arguments and the same return values. While passing a function as an argument to another function, the exact signature of the function has to be specified in the argument list. As in below example print function accept first argument which is a function of type func(int, int) int

func print(f func(int, int) int, a, b int)

Some more things to note about the below program

Code:

package main

import "fmt"

func main() {
    print(area, 2, 4)
    print(sum, 2, 4)
}

func print(f func(int, int) int, a, b int) {
    fmt.Println(f(a, b))
}

func area(a, b int) int {
    return a * b
}

func sum(a, b int) int {
    return a + b
}

Output

8
6