将函数作为参数传递

参数数量可变的函数称为为可变参数函数。典型的例子就是fmt.Printf和类似函数。Printf首先接收一个的必备参数,之后接收任意个数的后续参数。 在声明可变参数函数时,需要在参数列表的最后一个参数类型之前加上省略符号“…”,这表示该函数会接收任意数量的该类型参数。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. callback(1, Add)
  7. }
  8. func Add(a, b int) {
  9. fmt.Printf("The sum of %d and %d is: %d\n", a, b, a+b)
  10. }
  11. func callback(y int, f func(int, int)) {
  12. f(y, 5) // this becomes Add(1, 5)
  13. }

输出结果为:

  1. The sum of 1 and 5 is: 6