I am using reflection as a quick & dirty script handler but I can't figure out the error checking
How do I check that MethodByName has found a valid method?
Docs say zero value - what zero value?
anybody able to help?
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)
}
From standard docs:
The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns ""
So you want to use the IsValid method on the returned value from MethodByName. If it's false there was an error.