Higher-Order Function in Golang
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.
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.
Volume of Sphere is: 392.69908169872417
Please Login to comment...