如何从reflect.Value中获取结构字段

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

How to get struct field from refect.Value

问题

给定的代码片段如下:

  1. type Runnable interface {
  2. Run()
  3. }
  4. type T struct {
  5. Z struct {
  6. A int
  7. }
  8. }
  9. func (t T) Run() {
  10. t.Z.A = 1
  11. }
  12. func main() {
  13. t := reflect.TypeOf(T{})
  14. var v reflect.Value
  15. v = reflect.New(t).Elem()
  16. runnable := v.Interface().(Runnable)
  17. runnable.Run()
  18. }

在最后,有没有办法获取由Run()方法设置的Z及其字段值?

我正在实现一个API命令模式,所以T可以是RegisterCommandLoginCommandLogoutCommand等。Z是“输出文档”,即API命令返回的JSON文档,我希望能够声明性地指定并在命令运行后将其写入网络。

英文:

Given

  1. type Runnable interface {
  2. Run()
  3. }
  4. type T struct {
  5. Z struct {
  6. A int
  7. }
  8. }
  9. func (t T) Run() {
  10. t.Z.A = 1
  11. }
  12. func main() {
  13. t := reflect.TypeOf( T{} )
  14. var v reflect.Value
  15. v = reflect.New(t).Elem()
  16. runnable := v.Interface().(Runnable)
  17. runnable.Run()

Is there a way, at the end, to retrive Z and its field values as set by the Run() method?

I am implementing an API command pattern, so T could be RegisterCommand, LoginCommand, LogoutCommand etc. Z is the 'output doc' - a JSON doc returned by the API command - which I want to specify declaratively and have written to the network after the command is run.

答案1

得分: 1

明白了!感谢synful提供的“指针” 如何从reflect.Value中获取结构字段

  1. z := v.Elem().FieldByName("Z").Interface()
英文:

Got it! Thank you to synful for the 'pointer' 如何从reflect.Value中获取结构字段

  1. z := v.Elem().FieldByName("Z").Interface()

huangapple
  • 本文由 发表于 2014年12月9日 00:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/27362529.html
匿名

发表评论

匿名网友

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

确定