英文:
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可以是RegisterCommand、LoginCommand、LogoutCommand等。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提供的“指针” ![]()
    z := v.Elem().FieldByName("Z").Interface()
英文:
Got it! Thank you to synful for the 'pointer' ![]()
    z := v.Elem().FieldByName("Z").Interface()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论