mercredi 14 octobre 2015

Fill a struct from a map with reflection

I have a map of this kind type Store map[string]string

From this map, i would like to fill a struct. The goal is, for each field of the struct, find the key that match the field name, take the value, and based on the type of the struct field, convert the value to the proper struct field type and set it.

Basically the map will contains integers, booleans, strings and durations as strings so the convestion should be simply strconv.atoi(), time.parseDuration() ...

Also, i would like to use the structs tags to specify the name of the key in the map, because the struct field will be likely camelCase, while the keys in the map will be like this "example_key"

Any idea of how doing this. I have read about golang reflection but it is still opaque for me. I would just need an explanation to approach the problem, and then i think i can handle the implementation by my own.

Thanks





Aucun commentaire:

Enregistrer un commentaire