在go語言中,函數(shù)可以作為返回值使用,也可以作為參數(shù)使用。
比如
return math.Sqrt(x*x + y*y)
compute(math.Pow)
這樣的用法,在“map字典測試用例”中已經(jīng)見過了。下面再看一個相對簡單的示例
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作為參數(shù)使用
fmt.Println(reflect.TypeOf(hypot)) //打印hypot的數(shù)據(jù)類型
}
我們可以看到 hypot(3, 4) 和 compute(hypot) 是相同的執(zhí)行結(jié)果。它們執(zhí)行的都是 hypot 中的運算。
hypot究竟是什么類型呢?最后一行代碼可以打印出 hypot 的類型來。
我們一起看一下完整的運行結(jié)果
5
5
81
func(float64, float64) float64
第三個運行結(jié)果,是math.Pow使用了 compute 函數(shù)內(nèi)提供的參數(shù)(3, 4),進而求得了 3 的 4 次方。即 3 * 3 * 3 * 3 = 81