dongqin1861 2016-01-06 10:28
浏览 55
已采纳

无法获取通过反射调用的方法的返回字符串值

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

}
see this code in play.golang.org
  • 写回答

1条回答 默认 最新

  • dongliyan9190 2016-01-06 10:47
    关注

    .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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀