Reflection error on GoLang - Too few arguments

耗尽温柔 提交于 2019-12-04 09:42:15
Cito

I have found the answer by reading this:

https://stackoverflow.com/a/20715067/1339973

So instead of trying to call the method:

    methodInterface := finalMethod.Call([]reflect.Value{})[0].Interface()
    method_route := methodInterface.(func(r *http.Request) (string, int))
    body, code := method_route(r)

I just get the interface I need, then convert it into a function and call it as such.

    methodInterface := finalMethod.Interface()
    method_route := methodInterface.(func(r *http.Request) (string, int))
    body, code := method_route(r)

Actually, that is kind of what I was already doing, but in the wrong way.

VonC

As explained in "How to properly use .Call in reflect package, Golang?", and in reflect#Value.Call(), you need a slice with at least 1 element of the right type in it, if your function takes one parameter.

If you know the exact parameter type and value, you need to create it, and build your Call parameter:

 in := []reflect.Value{reflect.ValueOf(m)}

The exception "reflect: Call with too few input arguments" is called after checking the number of parameters expected by the function

NumIn returns a function type's input parameter count.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!