mardi 4 août 2020

Calling interface method after reflection & type switching in golang

I have struct

type ChartOpts struct {
    Name              mypakage.MyType
    Repo              mypakage.MyType
}

Ι want to iterate over its fields and if a type assertion is satisfied, called the method on that (asserted) type.

func (chartOpts ChartOpts) BindFlags(cobCom *cobra.Command) {
    fields := reflect.TypeOf(chartOpts)
    values := reflect.ValueOf(chartOpts)
    num := fields.NumField()
    fmt.Println(fields, values, num)
    for i := 0; i < num; i++ {
        field := fields.Field(i)
        switch v := field.Type.(type) {
        case mypackage.MyType:
            field.BindPersistentFlag(cobCom)
        default:
            log.Fatal(ErrUnhandledType)
        }
    }
    

}

The above code does not compile with this error:

field.BindPersistentFlag undefined (type reflect.StructField has no field or method BindPersistentFlag)

why?





Aucun commentaire:

Enregistrer un commentaire