我想定义一个函数来运行回调函数,并且该回调函数将是不确定的,例如args或返回值都是不确定的。
我尝试:
package main
import (
"fmt"
)
func F(callback func(args ...interface{}) interface{}, args ...interface{}) {
rev := callback(args...)
fmt.Println(rev)
}
func CB1() {
fmt.Println("CB1 called")
}
func CB2() bool {
fmt.Println("CB2 called")
return false
}
func CB3(s string) {
fmt.Println("CB3 called")
}
func CB4(s string) bool {
fmt.Println("CB4 called")
return false
}
func main() {
F(CB1)
F(CB2)
F(CB3, "xxx")
F(CB4, "yyy")
}
错误:
./play.go:31:3: cannot use CB1 (type func()) as type func(...interface {}) interface {} in argument to F
./play.go:32:3: cannot use CB2 (type func() bool) as type func(...interface {}) interface {} in argument to F
./play.go:33:3: cannot use CB3 (type func(string)) as type func(...interface {}) interface {} in argument to F
./play.go:34:3: cannot use CB4 (type func(string) bool) as type func(...interface {}) interface {} in argument to F
答案 0 :(得分:1)
可以,但是由于Go不支持泛型,因此必须将callback
定义为interface{}
类型。
要调用存储在callback
中的函数值,可以使用反射,即Value.Call()
方法。
它是这样的:
func F(callback interface{}, args ...interface{}) {
v := reflect.ValueOf(callback)
if v.Kind() != reflect.Func {
panic("not a function")
}
vargs := make([]reflect.Value, len(args))
for i, arg := range args {
vargs[i] = reflect.ValueOf(arg)
}
vrets := v.Call(vargs)
fmt.Print("\tReturn values: ")
for _, vret := range vrets {
fmt.Print(vret)
}
fmt.Println()
}
这样,您的应用程序的输出将是(在Go Playground上尝试):
CB1 called
Return values:
CB2 called
Return values: false
CB3 called
Return values:
CB4 called
Return values: false