Open In App

Higher-Order Function in Golang

Last Updated : 16 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In Go, language, a function is called a Higher-Order Function if it fulfills one of the following conditions:
1. Passing Functions as an Argument to Another Function:
If a function is passed as an argument to another function, then such types of functions are known as a Higher-Order function. This passing function as an argument is also known as a callback function or first-class function in the Go language. 
As shown in the below example, here Sphere() function takes a function as an argument and returns vol float64 as an argument. In the Main function, we create an anonymous function whose signature matches the parameter of Sphere function so, we simply call the Sphere() function and pass the result as an argument in it.
Example:
 

CSharp




// Golang program to illustrate how to pass
// a function as an argument to another
// function
package main
 
import (
    "fmt"
    "math"
)
 
// Volume function takes
// a function as a argument
func Sphere(vol func(radius float64) float64) {
 
    fmt.Println("Volume of Sphere is:", vol(3))
}
 
// Main Function
func main() {
 
    volume_of_sphere := func(radius float64) float64 {
        result := 4 / 3 * math.Pi * radius * radius * radius
        return result
    }
 
    // Passing function as an
    // argument in Volume function
    Sphere(volume_of_sphere)
}


Output:
 

Volume of Sphere is: 84.82300164692441

2. Returning Functions From Another Functions:
If a function returns another function, then such types of functions are known as a Higher-Order function. It is also known as the First-Class function. As shown in the below example, here Sphere() function returns an anonymous function that takes one float64 argument and returns a float64 argument. Now in the Main function, sVol stores the function return by Sphere() function, so we call sVol and pass one argument in it.
Example:
 

CSharp




// Golang program to illustrate how to pass
// a function returns another function
package main
 
import (
    "fmt"
    "math"
)
 
// Here, Volume function returns
// an anonymous function
func Sphere() func(radius float64) float64 {
 
    result := func(radius float64) float64 {
        volume := 4 / 3 * math.Pi * radius * radius * radius
        return volume
    }
 
    return result
 
}
 
// Main Function
func main() {
 
    sVol := Sphere()
    fmt.Println("Volume of Sphere is:", sVol(5))
}


Output: 
 

Volume of Sphere is: 392.69908169872417

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads