猿问

反射匿名结构域指针

我有一个这样的结构


type duration struct {

    time.Duration

}

还有一个这样的


type Config struct {

    Announce duration

}

我正在使用反射为结构配置的字段分配标志。但是,对于 type 的特定用例duration,我被卡住了。问题是,当我执行 switch 类型时,我得到了*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)

            }

        }

    }

}

谢谢


犯罪嫌疑人X
浏览 146回答 1
1回答

慕无忌1623718

好了,一些挖后,并感谢我的IDE,我发现,使用的方法elem()上ptr谁返回一个指针*time.Duration做的伎俩。如果我直接使用它也有效&ptr.Duration这是工作代码。func (d *duration) elem() *time.Duration {&nbsp; &nbsp; return &d.Duration}func assignFlags(v interface{}) {&nbsp; &nbsp; // Dereference into an adressable value&nbsp; &nbsp; xv := reflect.ValueOf(v).Elem()&nbsp; &nbsp; xt := xv.Type()&nbsp; &nbsp; for i := 0; i < xt.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; f := xt.Field(i)&nbsp; &nbsp; &nbsp; &nbsp; // Get tags for this field&nbsp; &nbsp; &nbsp; &nbsp; name := f.Tag.Get("long")&nbsp; &nbsp; &nbsp; &nbsp; short := f.Tag.Get("short")&nbsp; &nbsp; &nbsp; &nbsp; usage := f.Tag.Get("usage")&nbsp; &nbsp; &nbsp; &nbsp; addr := xv.Field(i).Addr().Interface()&nbsp; &nbsp; &nbsp; &nbsp; // Assign field to a flag&nbsp; &nbsp; &nbsp; &nbsp; switch ptr := addr.(type) {&nbsp; &nbsp; &nbsp; &nbsp; case *duration:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(short) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag.DurationVarP(ptr.elem(), name, short, 0, usage)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag.DurationVar(ptr.elem(), name, 0, usage)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答