A closure is a function value that references variables from outside
its body. The function may access and assign to the referenced
variables; in this sense the function is "bound" to the variables.
In your case, compute contains a closure function. Function is passed to the compute
function as an argument whose returned value is float64
which is then called in the compute function.
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4) // calling the function.
}
Since there are two functions created with same number of arguments, one of which is hypot
.
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
which takes two float64
values as an argument and then returns a float64
value, while another function is in package math
of golang which is math.pow
func Pow(x, y float64) float64 // Pow returns x**y, the base-x exponential of y.
whose definition is similar, which let us two pass any type of function as an argument to the compute function.
Take for an example on Go Playground