Search code examples
goreflectionreflect

Ignore case in golang reflection FieldByName


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?


Solution

  • 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.