Prashanth C
Prashanth C

Reputation: 21

Can anyone explain the compute(fn func()) code in the Go Tour website?

package main

import (
    "fmt"
    "math"
)

func compute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}

func main() {
    hypot := func(x, y float64) float64 {
        return math.Sqrt(x*x + y*y)
    }
    fmt.Println(hypot(5, 12))

    fmt.Println(compute(hypot))
    fmt.Println(compute(math.Pow))
}

Is the fn func() a function inside a function?? Can someone help with what is exactly the func compute doing here?. And I'm quite new to GO programming.

Upvotes: 1

Views: 2092

Answers (1)

Himanshu
Himanshu

Reputation: 12685

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

Upvotes: 3

Related Questions