问题描述
我在 http: 中找到了一个函数调用 MethodByName()
//golang.org/pkg/reflect/#Value.MethodByName 但这不是我想要的!(也许是因为我不知道如何使用它......我找不到任何例子).我想要的是:
I have found a function call MethodByName()
here http://golang.org/pkg/reflect/#Value.MethodByName but it's not exactly what I want! (maybe because I don't know how to use it ... I cannot find any example with it). What I want is:
type MyStruct struct {
//some feilds here
}
func (p *MyStruct) MyMethod {
println("My statement.");
}
CallFunc("MyStruct", "MyMethod");
//print out "My statement."
所以我想,首先我需要像 StructByName()
这样的东西,然后将它用于 MethodByName()
,是吗!?
So I guess, first I need something like StructByName()
and after that use it for MethodByName()
, is that right!?
推荐答案
要调用对象的方法,首先使用 reflect.ValueOf
.然后按名称查找方法,最后调用找到的方法.例如:
To call a method on an object, first use reflect.ValueOf
. Then find the method by name, and then finally call the found method. For example:
package main
import "fmt"
import "reflect"
type T struct {}
func (t *T) Foo() {
fmt.Println("foo")
}
func main() {
var t T
reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
}
这篇关于在 Go 中按名称调用结构及其方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!