4

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?

2
  • 2
    I would assume not, since you can have different fields in a struct with the same name with different capitalization.
    – robert
    Commented Jan 9, 2019 at 23:10
  • Golang also does not support property aliasing, to my knowledge.
    – Peter S
    Commented Jan 10, 2019 at 1:24

1 Answer 1

6

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.

1
  • An addition, now you can use strings.EqualFold function. Commented Jul 18, 2022 at 15:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.