函数值
函数值
函数也是值。它们可以像其它值一样传递。
函数值可以用作函数的参数或返回值。 package main import ( "fmt" "math" ) func compute(fn func(float64, float64) float64) float64 {//2. 接收到符合要求的函数 return fn(3, 4)//3. 执行hypot(3,4) 6. 返回hypot的结果 } func main() { hypot := func(x, y float64) float64 {//4. 收到符合要求的参数 return math.Sqrt(xx + yy)//5. 返回结果 } fmt.Println(hypot(5, 12)) fmt.Println(compute(hypot))//1. 进入函数computer,并且传入符合其规范的函数 7. 收到compute的结果 fmt.Println(compute(math.Pow))// 由于math.Pow的结构和上方函数相同,所以大致过程相同 } //结果 13 5 81 21
1 package
main 2 3 import ( 4
"fmt" 5
"math" 6 ) 7 8 func
compute ( fn
func ( float64 , float64 ) float64 ) float64 { //2. 接收到符合要求的函数 9
return
fn ( 3 , 4 ) //3. 执行hypot(3,4) 6. 返回hypot的结果 10 } 11 12 func
main () { 13
hypot :
func ( x , y
float64 ) float64 { //4. 收到符合要求的参数 14
return
math . Sqrt ( x * x
y * y ) //5. 返回结果 15
} 16
fmt . Println ( hypot ( 5 , 12 )) 17 18
fmt . Println ( compute ( hypot )) //1. 进入函数computer,并且传入符合其规范的函数 7. 收到compute的结果 19
fmt . Println ( compute ( math . Pow )) // 由于math.Pow的结构和上方函数相同,所以大致过程相同 20 } 21 //结果 22 13 23 5 24 81