Oop 使用反射调用方法并返回值
以关于的问题为出发点,我想按名称调用一个方法,并实际处理该值Oop 使用反射调用方法并返回值,oop,reflection,methods,go,Oop,Reflection,Methods,Go,以关于的问题为出发点,我想按名称调用一个方法,并实际处理该值 package main import "fmt" import "reflect" type T struct{} func (t *T) Foo() { fmt.Println("foo") } type MyStruct struct { id int } type Person struct { Name string Age int } func (t *T) Bar(ms *M
package main
import "fmt"
import "reflect"
type T struct{}
func (t *T) Foo() {
fmt.Println("foo")
}
type MyStruct struct {
id int
}
type Person struct {
Name string
Age int
}
func (t *T) Bar(ms *MyStruct, p *Person) int {
return p.Age
}
func main() {
var t *T
reflect.ValueOf(t).MethodByName("Foo").Call([]reflect.Value{})
var ans int
ans = reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value{reflect.ValueOf(&MyStruct{15}), reflect. ValueOf(&Person{"Dexter", 15})})
}
但是,我得到以下错误:
prog.go:30: cannot use reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value literal) (type []reflect.Value) as type int in assignment
[process exited with non-zero status]
我应该做些什么来实际返回一个值?我尝试使用类型转换并将其设置为
int
,但编译器说它不能[]反射.Value
调用
返回[]反射.Value
,这是一个片段。为了进行类型转换,需要从切片中获取元素。一旦您有了一个reflect.Value
实例,您就可以调用Int()
来获取作为int64的值
var ans int64
ans = reflect.ValueOf(t).MethodByName("Bar").Call([]reflect.Value{
reflect.ValueOf(&MyStruct{15}),
reflect.ValueOf(&Person{"Dexter", 15})})[0].Int()
fmt.Println(ans)