Welcome To Golang By Example

Higher-Order Functions in Go (Golang)

Overview

Higher-order functions are those functions that either accept a function as a type or return function. Since a function is a first-order variable in Golang they can be passed around and also returned from some function and assigned to a variable.

Code:

In below Example 1

Example 1

package main

import "fmt"

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

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

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

Output:

12

Example 2:

Let’s see one more little complex example where

package main

import "fmt"

func main() {
    add, subtract := getAddSubtract()
    print(3, 4, add, subtract)
}

func print(x, y int, add func(int, int) int, subtract func(int, int) int) {
    fmt.Printf("Sum is: %d\n", add(x, y))
    fmt.Printf("Difference Value is: %d\n", subtract(x, y))
}

func getAddSubtract() (func(int, int) int, func(int, int) int) {
    add := func(x, y int) int {
        return x + y
    }
    subtract := func(x, y int) int {
        return x - y
    }
    return add, subtract
}

Output:

Sum is: 7
Difference Value is: 1