在Go语言中,函数可以作为返回值使用,也可以作为参数使用。
比如
return math.Sqrt(x*x + y*y)...compute(math.Pow)
示例
package mainimport ("fmt""math""reflect")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) //math.Sqrt作为返回值使用}fmt.Println(hypot(3, 4))fmt.Println(compute(hypot))fmt.Println(compute(math.Pow)) //math.Pow作为参数使用fmt.Println(reflect.TypeOf(hypot)) //打印hypot的数据类型}
我们可以看到hyopt(3,4)和compute(hyopt)是相同的执行结果。它们执行的都是hyopt中的运算。
hypot究竟是什么类型呢?最后一行代码可以打印出hypot的类型来。
运行结果
5581func(float64, float64) float64
第三个运行结果,是math.Pow使用了 compute 函数内提供的参数(3, 4),进而求得了 3 的 4 次方。即 3 3 3 * 3 = 81

