Go 如何使用reflect包访问函数的返回数据?
我有一个IndexController类型的函数:Go 如何使用reflect包访问函数的返回数据?,go,Go,我有一个IndexController类型的函数: func (this IndexController) ActionIndex() map[string]string { return map[string]string{"Name": "Hello from the actionIndex()!"} } 它的用途是: routerInstance := router.Constructor(request) controllerObject := controllers[rou
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"
我会感激的 首先,返回一个[]reflect.Value
,因此您需要对其进行索引以获得实际返回值:
outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{})[0]
(注意行末尾的[0]
)
从那时起,您可能需要执行类型切换或接口转换,如outputData.(map[string]interface{})
,以获得可以按字符串索引的映射
如果你能提供你的整个
服务器。转到文件,或者把它放在上面,那会有帮助。我找到了一个解决方案。我们必须使用outputData.Interface()。