我如何在Golang中传递函数作为参数,该函数可能具有多个参数,例如fmt.Printf

第一个问题是必须定义要首先传递的函数的类型。

type FunctionWithVariableArgumentLength func(s string, object1 type1, ..., objectn typen)

第二个问题是,不知道列表中的参数可能具有什么类型,例如fmt.Printf

最佳答案

其他功能都有一个原型(prototype):http://golang.org/pkg/fmt/#Printf

因此,您可以定义将函数作为参数接受的函数,如下所示:

func exe(f func(string, ...interface{}) (int, error)) {
    f("test %d", 23)
}
func main() {
    exe(fmt.Printf)
}

Demonstration

10-07 19:08
查看更多