首页 > 解决方案 > 如何通过字符串变量调用方法?

问题描述

我以前在这里看到过这个问题。但我不明白答案。

如何从字符串值调用方法。所以如果

我有很多方法是

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

每个参数类型相同。没有回报等......从字面上看,方法名称的唯一区别。

我想做这样的事情,但我无法让它工作。我只想从“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)})
}

我显然不明白反射是如何工作的。

标签: goreflection

解决方案


如果您导出该方法,则您的示例有效。更改fooFoo

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

这将输出(在Go Playground上尝试):

Foo..

另请注意,在此示例Foo()中具有 value receiver: c something。如果方法有指针接收器如c *something,则需要有一个指针值开头,因为带有指针接收器的方法不在非指针类型的方法集中。

参见相关:调用具有特殊前缀/后缀的函数


推荐阅读