我以前在这里看到过这个问题。但是我不明白答案。
如何从字符串值调用方法。所以如果
我有很多方法
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)})
}
我显然不明白反射是如何工作的。
最佳答案
如果导出该方法,则示例适用。将foo
更改为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)})
}
这将输出(在Go Playground上尝试):
Foo..
还要注意,在此示例中,
Foo()
具有值接收者:c something
。如果该方法具有指针接收器(例如c *something
),则您需要具有一个指针值开头,因为具有指针接收器的方法不在非指针类型的method set中。参见相关:Call functions with special prefix/suffix
关于go - 如何通过字符串变量调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61613876/