doulou1989 2014-12-08 16:35
浏览 9
已采纳

如何从refect.Value获取结构字段

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条回答 默认 最新

  • dongyi0114 2014-12-09 00:26
    关注

    Got it! Thank you to synful for the 'pointer' :-)

        z := v.Elem().FieldByName("Z").Interface()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题