将函数作为参数传递
参数数量可变的函数称为为可变参数函数。典型的例子就是fmt.Printf和类似函数。Printf首先接收一个的必备参数,之后接收任意个数的后续参数。 在声明可变参数函数时,需要在参数列表的最后一个参数类型之前加上省略符号“…”,这表示该函数会接收任意数量的该类型参数。
package mainimport ("fmt")func main() {callback(1, Add)}func Add(a, b int) {fmt.Printf("The sum of %d and %d is: %d\n", a, b, a+b)}func callback(y int, f func(int, int)) {f(y, 5) // this becomes Add(1, 5)}
输出结果为:
The sum of 1 and 5 is: 6