我正在使用反射作为一个快速而肮脏的脚本处理程序,但我无法弄清楚错误检查
如何检查 MethodByName 是否找到了有效方法?
文档说零值 - 什么是零值?
有人能帮忙吗?
https://play.golang.org/p/ogypx-wLay
type step struct {
Action string
Parameter string
Second string
}
func doStep(little step) (err error) {
apiR := reflect.ValueOf(skript{})
apiF := apiR.MethodByName(little.Action)
if apiF == reflect.Zero(reflect.TypeOf(skript.Approve)) {
return errors.New("xxx")
}
args := []reflect.Value{reflect.ValueOf(little.Parameter), reflect.ValueOf(little.Second)}
apiF.Call(args)
return nil
}
type skript struct{}
func (skript) Approve(who string, dummy string) {
fmt.Println("Approve ", who, dummy)
}
func main() {
st1 := step{"Approve", "me", "ok"}
st2 := step{"Block", "me", "ok"}
doStep(st1)
doStep(st2)
}
最佳答案
来自标准文档:
The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns ""
因此,您想对 MethodByName 的返回值使用 IsValid 方法。如果它是 false,则表示有错误。
关于go - 如何使用 MethodByName 检查实际函数是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010827/