英文:
Using reflection to call a method and return a value
问题
使用关于按名称调用方法的问题作为起点,我想通过名称调用一个方法,并实际对值进行操作。
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
,但编译器说它不能是[]reflect.Value
。
英文:
Using the question about calling a method by name as a starting point, I wanted to call a method by name and actually do something with the value.
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})})
}
Playground link, http://play.golang.org/p/e02-KpdQ_P
However, I get the following error:
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]
What should I do differently to actually return a value? I tried using type conversion and making it an int
, but the compiler said that it couldn't []reflect.Value
.
1: https://stackoverflow.com/questions/8103617/call-a-struct-and-its-method-by-name-in-go
2: http://play.golang.org/p/e02-KpdQ_P
答案1
得分: 3
Call
返回的是一个[]reflect.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)
英文:
Call
returns []reflect.Value
which is a slice. You need to get an element from the slice in order to do the type conversion. Once you have a reflect.Value
instance you can call Int()
to get the value as an 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论