Go基础(复杂类型):函数值

函数值

函数也是值。它们可以像其它值一样传递。
函数值可以用作函数的参数或返回值。


一、下面来看一个函数值的例子

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 {
        //a=169
        a := x*x + y*y
        //这个地方是求平方根
        return math.Sqrt(a)
    }
    fmt.Println(hypot(5, 12))

    //这个地方是5
    fmt.Println(compute(hypot))

    //math.Pow()是x的y次幂
    //这里就是3的4次幂
    fmt.Println(compute(math.Pow))
}

输出结果:

API server listening at: 127.0.0.1:61828
13
5
81

猜你喜欢

转载自blog.csdn.net/wd2014610/article/details/80670756