函数作为参数,函数是第一类对象,可作为参数传递,只要被调用函数的返回值个数,返回值类型和返回值的顺序与调用函数所需要的实参是一致的,就可以吧这个被调用 的函数当做其他函数的参数。
func f1(a,b,c int)
func f2(a,b int)(int,int,int)
func f1(f2(a,b))函数f1需要三个参数,同时f2返回三个参数
package main
import "fmt"
func pipe(ff func() int) int {
return ff()
}
type FormatFunc func(s string, x, y int) string
func format(ff FormatFunc, s string, x, y int) string {
return ff(s, x, y)
}
func main() {
s1 := pipe(func() int { return 100 })
s2 := format(func(s string, x, y int) string {
return fmt.Sprintf(s, x, y)
}, "%d,%d", 10, 20)
fmt.Println(s1, s2)
}
有返回值的函数,必须有明确的终止语句。
函数作为类型
函数go语言中也是一种变量,前面多次通过type来定义它,它的类型就是所有拥有相同参数与相同返回值的一种函数类型
type typeName func(input1 inputType1,inp