反射匿名结构字段指针

Reflection anonymous struct field pointer

我有这样的结构

type duration struct {
    time.Duration
}

还有一个类似的

type Config struct {
    Announce duration
}

我正在使用反射将标志分配给结构配置的字段。但是,对于 duration 类型的特定用例,我被卡住了。 问题是当我做一个开关类型时,我得到的是 *config.duration 而不是 *time.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) { // 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)
            }
        }
    }
}

谢谢

好的,经过一番挖掘,感谢我的 IDE,我发现在 ptr 上使用方法 elem() 谁 return 一个指针 *time.Duration 做的伎俩。如果我直接使用 &ptr.Duration

它也有效

这是工作代码。

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)
            }
        }
    }
}