mercredi 19 mai 2021

Getting map entries using reflection in Golang

I want to get maps entries of type <string, interface{}> using reflection. The value of those entries could be of native types (string, int, float, etc.) or Time. I use those maps to allow passing miscellaneous data to error logs. Up till now, I tried using reflect Value, but I cannot execute Value.Interface on those values of type interface{}, so I am not able to get the value. I, also, tried using Value.MapKeys but I was not successful.

The code that I tried was this:

keys := mapValue.MapKeys()
for _, key := range keys {
    mapValue.MapIndex(key)
}

But, the

mapValue.MapIndex(key).CanInterface()

is false. So, I cannot get the value.

How could I get those values from the map?

Update: I was able to have it working using this:

var logFields []log.Field
keys := mapValue.MapKeys()
for _, key := range keys {
    entryValue := mapValue.MapIndex(key)
    logFields = append(logFields, log.String(key.String(), fmt.Sprintf("%#v", entryValue)))
}

The only thing that I cannot get is Time string value.





Aucun commentaire:

Enregistrer un commentaire