簡體   English   中英

如何正確使用.Call反映包

[英]How to properly use .Call in reflect package

我的代碼最后一個問題涉及到反射包中的.Call函數。

所以我正在打這樣的電話:

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

我正在制作.Call的方法如下:

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

我不太明白的是如何操縱“in”變量以便將我需要的地圖正確傳遞到函數中。 我看到make()中的第二個參數是參數的長度? 但我不太明白如何格式化變量以正確傳遞我的參數。 我遞歸地運行錯誤消息:

reflect: Call with too few input arguments

任何幫助將非常感激!

Value.Call documentation

調用帶有輸入參數的函數v 。例如,如果len(in) == 3 ,則v.Call(in)表示Go調用v(in[0], in[1], in[2])

所以,如果你想調用一個函數帶有一個參數, in必須包含一個reflect.Value正確類型的,你的情況map[string][]string

表達方式

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

創建一個長度為0的切片。將此Value.Call傳遞給Value.Call將導致您收到的恐慌,因為您需要1個參數,而不是零。

正確的電話會是:

m := map[string][]string{"foo": []string{"bar"}}

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

myMethod.Call(in)

該調用試圖將零參數傳遞給期望一個參數的控制器( in是一個空切片)。 你需要做更多的事情in := []reflect.Value{reflect.ValueOf(params)}

一旦找到方法,你也可以調用.Interface() ,然后使用類型斷言來獲取你可以直接調用的func

// get a reflect.Value for the method
methodVal := reflect.ValueOf(&controller_ref).MethodByName(action_name)
// turn that into an interface{}
methodIface := methodVal.Interface()
// turn that into a function that has the expected signature
method := methodIface.(func(map[string][]string) map[string]string)
// call the method directly
res := method(params)

(然后你甚至可以在方法名稱鍵入的地圖中緩存 method ,因此你不必在下次調用時進行reflect操作。但是你不必這樣做才能使它工作。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM