Function values

Functions are values too. They can be passed around just like other values.

Function values may be used as function arguments and return values.

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. }