英文:
Can't get returning string value of a method called via reflection
问题
无法通过反射调用的方法获取返回的字符串值
恐慌:接口转换:接口是[]reflect.Value,而不是字符串
package main
import (
"reflect"
)
type API_EndPoint struct{}
func main() {
var ep API_EndPoint
s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})
v := reflect.ValueOf(s)
i := v.Interface()
a := i.(string)
println(a)
}
func (ep *API_EndPoint) EndPoint_X(params string) string {
return "this_is_a_string" + params
}
英文:
Can't get returning string value of a method called via reflection
panic: interface conversion: interface is []reflect.Value, not string
package main
import (
"reflect"
)
type API_EndPoint struct{}
func main() {
var ep API_EndPoint
s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})
v := reflect.ValueOf(s)
i := v.Interface()
a := i.(string)
println(a)
}
func (ep *API_EndPoint) EndPoint_X(params string) string {
return "this_is_a_string" + params
}
<iframe src="https://play.golang.org/p/3yJ5jAb9-2" frameborder="0" style="width: 100%; height: 100%"><a href="https://play.golang.org/p/3yJ5jAb9-2">see this code in play.golang.org</a></iframe>
答案1
得分: 2
.Call
返回一个reflect.Value
的切片,所以为了实现你想要的效果,你需要像这样做:
package main
import "reflect"
type API_EndPoint struct {}
func main() {
var ep API_EndPoint
s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf("foo bar")})
v := reflect.ValueOf(s)
i := v.Interface()
a := i.([]reflect.Value)[0].String() // 获取切片的第一个索引,并调用它的.String()方法
println(a)
}
func (ep *API_EndPoint) EndPoint_X(params string) string {
return "this_is_a_string " + params
}
https://play.golang.org/p/MtqCrshTcH
this_is_a_string foo bar
不确定你想要实现什么,但这应该可以工作。
英文:
.Call
returns a slice
of reflect.Value
so to do what you're trying to do you need to do something like:
package main
import ("reflect")
type API_EndPoint struct {}
func main() {
var ep API_EndPoint
s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})
v := reflect.ValueOf(s)
i := v.Interface()
a := i.([]reflect.Value)[0].String() // Get the first index of the slice and call the .String() method on it
println(a)
}
func (ep *API_EndPoint) EndPoint_X( params string) string{
return "this_is_a_string " + params
}
https://play.golang.org/p/MtqCrshTcH
> this_is_a_string foo bar
Not sure what you're trying to accomplish but that should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论