如何正确使用。在Golang的反映包中调用? [英] How to properly use .Call in reflect package, Golang?
问题描述
我的代码涉及反映包中的.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变量以正确传递地图I需要进入功能。我看到make()中的第二个参数是参数的长度?但我不太了解如何格式化变量,以便正确传入我的参数。
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!
推荐答案
从 Value.Call文件
:
拨打例如,如果
len(in)== 3
,<$>v
c $ c> v.Call(in)代表Go呼叫v(在[0]中,在[1]中,在[2]中)
。
Call calls the function
v
with the input arguments in. For example, iflen(in) == 3
,v.Call(in)
represents the Go callv(in[0], in[1], in[2])
.
所以如果你想用一个参数调用一个函数,中的必须包含
右类型的一个 reflect.Value
,在你的情况下 map [string] [] string
。
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)
创建长度为0的分片。将其传递给 Value.Call
会导致恐慌,因为您
需要1个参数,而不是零。
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.
正确的调用将会是:
m := map[string][]string{"foo": []string{"bar"}}
in := []reflect.Value{reflect.ValueOf(m)}
myMethod.Call(in)
这篇关于如何正确使用。在Golang的反映包中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!