dongmu2026 2013-12-21 02:57 采纳率: 100%
浏览 69
已采纳

如何正确使用。调用反射包

Been having one last issue with my code which involves the .Call function in the reflect package.

So I'm making a call such as this:

params := "some map[string][]string"
in := make([]reflect.Value,0)
return_values := reflect.ValueOf(&controller_ref).MethodByName(action_name).Call(in)

where the method I'm making the .Call to is as follows:

func (c *Controller) Root(params map[string][]string) map[string] string{}

What I don't quite understand is how to manipulate the "in" variable in order to properly pass the map I need to into the function. I see that the second parameter in the make() is the length of the parameter? But I don't quite understand how to format the vars in order to properly pass in my parameter. I am recursively running into the error message:

reflect: Call with too few input arguments

Any help would be much appreciated!

  • 写回答

2条回答 默认 最新

  • dsjws44266 2013-12-21 03:24
    关注

    From the Value.Call documentation:

    Call calls the function v with the input arguments in. For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).

    So if you want to call a function with one parameter, in must contain one reflect.Value of the right type, in your case map[string][]string.

    The expression

    in := make([]reflect.Value,0)
    

    creates a slice with length 0. Passing this to Value.Call will result in the panic you receive as you need 1 parameter, not zero.

    The correct call would be:

    m := map[string][]string{"foo": []string{"bar"}}
    
    in := []reflect.Value{reflect.ValueOf(m)}
    
    myMethod.Call(in)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题