2

I am trying read from a struct using reflection in golang which I was able to do successfully but I am wondering what can I do to ignore case of a field name.

I have the below code

type App struct{
    AppID        string
    Owner        string
    DisplayName  string
}

func Extract(app *App){
appData := reflect.ValueOf(app)
appid := reflect.Indirect(appData).FieldByName("appid")
fmt.Println(appid.String())
owner:=reflect.Indirect(appData).FieldByName("owner")
fmt.Println(owner.String())
}

The above function returns <invalid-value> for both and its because of the lower case of the field name

Is there a way I could ignore the case?

DoIt
  • 2,788
  • 7
  • 38
  • 78

1 Answers1

5

Use Value.FieldByNameFunc and strings.ToLower to ignore case when finding a field:

func caseInsenstiveFieldByName(v reflect.Value, name string) reflect.Value {
    name = strings.ToLower(name)
    return v.FieldByNameFunc(func(n string) bool { return strings.ToLower(n) == name })
}

Use it like this:

func Extract(app *App) {
    appData := reflect.ValueOf(app)
    appid := caseInsenstiveFieldByName(reflect.Indirect(appData), "appid")
    fmt.Println(appid.String())
    owner := caseInsenstiveFieldByName(reflect.Indirect(appData), "owner")
    fmt.Println(owner.String())
}

Run it on the Playground.

Cerise Limón
  • 88,331
  • 8
  • 164
  • 179