你可以使用反射包(reflect package)来访问函数返回的数据。

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年4月20日 17:01:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/23180307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定