厚土Go学习笔记 | 25. 函数值 函数是函数也是值

时间:2022-05-06
本文章向大家介绍厚土Go学习笔记 | 25. 函数值 函数是函数也是值,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在go语言中,函数可以作为返回值使用,也可以作为参数使用。

比如

return math.Sqrt(x*x + y*y)
...
compute(math.Pow)

这样的用法,在map字典测试用例中已经见过了。下面再看一个相对简单的示例

package main

import (
    "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的数据类型
}

我们可以看到 hypot(3, 4)compute(hypot) 是相同的执行结果。它们执行的都是 hypot 中的运算。

hypot究竟是什么类型呢?最后一行代码可以打印出 hypot 的类型来。

我们一起看一下完整的运行结果

5
5
81
func(float64, float64) float64

第三个运行结果,是math.Pow使用了 compute 函数内提供的参数(3, 4),进而求得了 3 的 4 次方。即 3 * 3 * 3 * 3 = 81