Welcome To Golang By Example

User defined function types in Go (Golang)

Overview

In GO, the function is also a type. Two functions will be of the same type if

Function as user-defined type can be declared using the type keyword like below. area is the name of the function of type func(int, int) int

type area func(int, int) int

Code

Example 1

In this example, we create a user-defined function type area. Then we create a variable of type area in the main function.

package main

import "fmt"

type area func(int, int) int

func main() {
    var areaF area = func(a, b int) int {
        return a * b
    }
    print(2, 3, areaF)
}

func print(x, y int, a area) {
    fmt.Printf("Area is: %d\n", a(x, y))
}

Output:

6

Example 2

In this example also we create a user-defined function type area. Then we create a function getAreaFunc() which returns the function of type area

package main

import "fmt"

type area func(int, int) int

func main() {
    areaF := getAreaFunc()
    print(2, 3, areaF)

}

func print(x, y int, a area) {
    fmt.Printf("Area is: %d\n", a(x, y))
}

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

Output:

6