Several Methods to Convert
There are several methods to convert map[string]interface{}
to a struct
in Go.
- Using
reflect
. This is the fastest. But, it will produce complicated long code. If not well coded, it will have problems with nested map. I will not discuss this method. - Using
json
standard library. First we marshal the map as json string and after that unmarshal it as a struct. This is what I will be talking about. It is slow, but reliable. Nested map are handled performantly. - Using external library such as mitchellh/mapstructure. It is not maintained anymore. But, you can still use it, since it is stable and has achieved its original intention.
- Using simple loop and check one by one using
switch
-case
. You need to hard-coded all the map properties, hence it’s not practical since it can’t be reused for different struct type.
Converting to Struct
The code below is the original non-generic method that can be used to
convert any map to string. Don’t forget to include the json tag as per your
intention, so the json
library can convert it correctly.