mardi 5 mai 2020

In Go, how do I call a method by string variable?

I've seen this asked here before. But I don't understand the answers.

How do I call a method from a string value. So if the

I have many methods that are

func (c *something) whateverName(whatever map[string]interface{}) {
}

Same argument type in each one. no returns etc... Literally the only difference in the method name.

I'm looking to do something like this, and I just can't get it to work. I just want to call the correct method from the value of "var myMethod string":

func (c something) foo(m map[string]interface{}) {
 fmt.Println("foo..")
 //do something with m
}

func main() {
 myMethod := "foo"
 message := make(map[string]interface{})
 //fill message with stuff...
 c := something{} //this is just a hypothetical example...
 vt := reflect.ValueOf(c)
 vm := vt.MethodByName(myMethod)    
 vm.Call([]reflect.Value{reflect.ValueOf(message)})
}

I'm obviously not understanding how reflection works.





Aucun commentaire:

Enregistrer un commentaire