Go 函数

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

比如

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


示例

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

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

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

 

运行结果

5
5
81
func(float64, float64) float64

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

 

参考:

https://www.yuque.com/docs/share/4fb3864c-7bd7-4d8f-9313-256ae66d1462

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值