英文:
How I can access to a returned data of a function with use the reflect package?
问题
我有一个 IndexController 类型的函数:
func (this IndexController) ActionIndex() map[string]string {
return map[string]string{"Name": "Hello from the actionIndex()!"}
}
它的使用方式如下:
routerInstance := router.Constructor(request)
controllerObject := controllers[routerInstance.GetRequestController(true)]
outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{})
fmt.Println(outputData)
现在,例如如何显示 outputData 的 Name 元素?我尝试这样打印:
fmt.Println(outputData["Name"])
但程序会报错退出:
# command-line-arguments
./server.go:28: non-integer array index "Name"
谢谢!
英文:
I have a function of the IndexController type:
func (this IndexController) ActionIndex() map[string]string {
return map[string]string{"Name": "Hello from the actionIndex()!"}
}
It is used so:
routerInstance := router.Constructor(request)
controllerObject := controllers[routerInstance.GetRequestController(true)]
outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{})
fmt.Println(outputData)
Now for example, how to show the Name element of outputData? I try to print so:
fmt.Println(outputData["Name"])
But program will exit with error:
# command-line-arguments
./server.go:28: non-integer array index "Name"
I will be thankful!
答案1
得分: 0
首先,(v Value) Call(…)
返回一个 []reflect.Value
,所以你需要对它进行索引以获取实际的返回值:
outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{})[0]
(注意行尾的 [0]
)
从那里开始,你可以使用类型切换或者接口转换,比如 outputData.(map[string]interface{})
,以获取一个可以通过字符串索引的映射。
如果你能提供完整的 server.go
文件,或者将其放在 play.golang.org 上,那会更有帮助。
英文:
First, (v Value) Call(…)
returns a []reflect.Value
, so you need to index it to get your actual return value:
outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{})[0]
(note the [0]
at the end of the line)
From there on, you could probably do a type switch or maybe an interface conversion like outputData.(map[string]interface{})
to get a map that you can index by string.
It would help though if you would provide your entire server.go
file, or maybe put it up on play.golang.org.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论