函数值

函数也是值。它们可以像其它值一样传递。

函数值可以用作函数的参数或返回值。

function-values.go

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func compute(fn func(float64, float64) float64) float64 {
  7. return fn(3, 4)
  8. }
  9. func main() {
  10. hypot := func(x, y float64) float64 {
  11. return math.Sqrt(x*x + y*y)
  12. }
  13. fmt.Println(hypot(5, 12))
  14. fmt.Println(compute(hypot))
  15. fmt.Println(compute(math.Pow))
  16. }