有没有办法定义一个函数可以运行Golang中的任何回调函数?
我想定义一个函数来运行回调函数,而回调函数是不确定的,例如args或returns都是不确定的 我试试这个:有没有办法定义一个函数可以运行Golang中的任何回调函数?,go,Go,我想定义一个函数来运行回调函数,而回调函数是不确定的,例如args或returns都是不确定的 我试试这个: package main import ( "fmt" ) func F(callback func(args ...interface{}) interface{}, args ...interface{}) { rev := callback(args...) fmt.Println(rev) } func CB1() { fmt.Println
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
可以,但由于Go不支持泛型,因此必须将
callback
定义为interface{}
类型
要调用存储在回调中的函数值,可以使用反射,即方法
这就是它的样子:
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()
}
使用此选项,应用程序的输出将是(在上尝试):
这感觉像是一场灾难。是否有一个潜在的问题,我们可以帮助您以更惯用的方式解决?
CB1 called
Return values:
CB2 called
Return values: false
CB3 called
Return values:
CB4 called
Return values: false