[英]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
}
在play.golang.org中看到此代码
.Call
返回slice
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() // 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
不知道您要完成什么,但这应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.