1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Chemdream
  • 618
  • 2
  • 9
  • 25

1 Answers1

4

Your example works if you export the method. Change foo to Foo:

type something struct{}

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

This will output (try it on the Go Playground):

Foo..

Also note that in this example Foo() has value receiver: c something. If the method has a pointer receiver such as c *something, you need to have a pointer value to start with, because a method with a pointer receiver is not in the method set of the non-pointer type.

See related: Call functions with special prefix/suffix

icza
  • 389,944
  • 63
  • 907
  • 827
  • @Chemdream, do you really need reflection? Won't simple map which maps names to methods work for you? I'd be much simpler to understand for the next programmer to work with you code (including you six month later), and probably faster, too. – kostix May 05 '20 at 13:14
  • @kostix post a simple example? – Chemdream May 05 '20 at 14:17