vendredi 30 avril 2021

Dynamically Access Nested struct values

I am trying to access a property based on the path i get from the database:

for example in struct Vehicle,


type Vehicle struct {
    core.Model
    Manufacturer Manufacturer
    VehicleNumber string
.....
}

type Manufacturer struct {
    ManufacturerName string
....
}

i want to fetch

value := exportValueFromField(vehicle,"Manufacturer.ManufacturerName")
    func exportValueFromField(data interface{}, index string) string {
       indexArray := strings.Split(index, ".")
       r := reflect.ValueOf(data)
       for _, i := range indexArray {
          if r.FieldByName(i).Kind() == reflect.Struct {
            r = reflect.ValueOf(r.FieldByName(i).Interface())
          }else {
            r = r.FieldByName(i)
          }
       }
       return fmt.Sprintf("%v", r)
   }

But it doesn't seem to work





Aucun commentaire:

Enregistrer un commentaire