dssj88098 2018-09-21 10:40
浏览 151
已采纳

谁能在Go Tour网站上解释一下compute(fn func())代码吗?

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.

  • 写回答

1条回答 默认 最新

  • dsrjs86444 2018-09-21 11:03
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀