Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 如何使用reflect包访问函数的返回数据?_Go - Fatal编程技术网

Go 如何使用reflect包访问函数的返回数据?

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

我有一个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)
例如,现在如何显示outputDataName元素?我尝试打印,以便:

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()。