问题描述
我的代码遇到了最后一个问题,该问题涉及反射包中的.Call函数.
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)
我调用.call的方法如下:
where the method I'm making the .Call to is as follows:
func (c *Controller) Root(params map[string][]string) map[string] string{}
我不太了解的是如何操作"in"变量,以便将所需的映射正确传递到函数中.我看到make()中的第二个参数是参数的长度吗?但是我不太了解如何格式化var以便正确传递我的参数.我递归地遇到错误消息:
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!
推荐答案
因此,如果要使用一个参数调用函数,则in
必须包含一个reflect.Value
正确的类型,以您的情况为map[string][]string
.
So if you want to call a function with one parameter, in
must contain one reflect.Value
of theright type, in your case map[string][]string
.
表达式
in := make([]reflect.Value,0)
创建一个长度为0的切片.将其传递给Value.Call
会导致您在收到恐慌时需要1个参数,而不是零.
creates a slice with length 0. Passing this to Value.Call
will result in the panic you receive as youneed 1 parameter, not zero.
正确的呼叫应该是:
m := map[string][]string{"foo": []string{"bar"}}
in := []reflect.Value{reflect.ValueOf(m)}
myMethod.Call(in)
这篇关于如何正确使用.调用反射包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!