lundi 22 mai 2017

How to check if the actual function exists using MethodByName?

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?

http://ift.tt/2qt8JO2

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)
}





Aucun commentaire:

Enregistrer un commentaire