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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀