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

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

How to get struct field from refect.Value

问题

给定的代码片段如下:

type Runnable interface {
    Run()
}

type T struct {
    Z struct {
        A int
    }
}

func (t T) Run() {
    t.Z.A = 1
}

func main() {
    t := reflect.TypeOf(T{})

    var v reflect.Value
    v = reflect.New(t).Elem()

    runnable := v.Interface().(Runnable)
    runnable.Run()
}

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

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

英文:

Given

type Runnable interface {
     Run()
}

type T struct {
    Z struct {
        A int
    }
}

func (t T) Run() {
    t.Z.A = 1
}

func main() {
    t := reflect.TypeOf( T{} )

    var v reflect.Value
    v = reflect.New(t).Elem()

    runnable := v.Interface().(Runnable)
    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中获取结构字段

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

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

    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:

确定