dougu7546 2015-10-15 22:59
浏览 40
已采纳

反射匿名结构字段指针

I have a struct like this

type duration struct {
    time.Duration
}

and another one like that

type Config struct {
    Announce duration
}

I am using reflection to assign flags to the fields of the struct Config. However, with the particular use case of the type duration, i am stuck. The problem is that when i do a switch type, i got *config.duration instead of *time.Duration. How can i access the anonymous field ?

Here is the full code

func assignFlags(v interface{}) {

    // Dereference into an adressable value
    xv := reflect.ValueOf(v).Elem()
    xt := xv.Type()

    for i := 0; i < xt.NumField(); i++ {
        f := xt.Field(i)

        // Get tags for this field
        name := f.Tag.Get("long")
        short := f.Tag.Get("short")
        usage := f.Tag.Get("usage")

        addr := xv.Field(i).Addr().Interface()

        // Assign field to a flag
        switch ptr := addr.(type) { // i get `*config.duration` here
        case *time.Duration:
            if len(short) > 0 {
                // note that this is not flag, but pflag library. The type of the first argument muste be `*time.Duration`
                flag.DurationVarP(ptr, name, short, 0, usage)
            } else {
                flag.DurationVar(ptr, name, 0, usage)
            }
        }
    }
}

Thanks

  • 写回答

1条回答 默认 最新

  • doupo1865 2015-10-15 23:45
    关注

    Okay, after some digging, and thanks to my IDE, i found that using a method elem() on ptr who return a pointer *time.Duration do the trick. It also work if i directly use &ptr.Duration

    Here is the working code.

    func (d *duration) elem() *time.Duration {
        return &d.Duration
    }
    
    func assignFlags(v interface{}) {
    
        // Dereference into an adressable value
        xv := reflect.ValueOf(v).Elem()
        xt := xv.Type()
    
        for i := 0; i < xt.NumField(); i++ {
            f := xt.Field(i)
    
            // Get tags for this field
            name := f.Tag.Get("long")
            short := f.Tag.Get("short")
            usage := f.Tag.Get("usage")
    
            addr := xv.Field(i).Addr().Interface()
    
            // Assign field to a flag
            switch ptr := addr.(type) {
            case *duration:
                if len(short) > 0 {
                    flag.DurationVarP(ptr.elem(), name, short, 0, usage)
                } else {
                    flag.DurationVar(ptr.elem(), name, 0, usage)
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题