Safely Handling Arbitrary Data
Let’s learn how the map[string]interface{} map enables us to deal with arbitrary data.
We have a utility that processes its command-line arguments; if everything goes as expected, then we get the supported types of command-line arguments, and everything goes smoothly. But what happens when something unexpected occurs? In that case, the map[string]interface{}
map is here to help, and this lesson shows how!
Rationale for map[string]interface{}
Remember that the biggest advantage we get from using a map[string]interface{}
map, or any map that stores an interface{}
value, in general, is that we still have our data in its original state and data type. If we use map[string]string
instead, or anything similar, then any data we have is going to be converted into a string
, which means that we are going to lose information about the original data type and the structure of the data we are storing in the map.
How map[string]interface{}
works
Nowadays, web services work by exchanging JSON records. If we get a JSON record in a supported format, then we can process it as expected, and everything will be fine. However, there are times when we might get an erroneous record or a record in an unsupported JSON format. In these cases, using map[string]interface{}
for storing these unknown JSON records (arbitrary data) is a good choice because map[string]interface{}
is good at storing JSON records of an unknown type.
Coding example
We are going to illustrate this technique using a utility named mapEmpty.go
that processes arbitrary JSON records given as command-line arguments. We process the input JSON record in two ways that are similar but not identical. There is no real difference between the exploreMap()
, and typeSwitch()
functions apart from the fact that typeSwitch()
generates a much richer output. The code of mapEmpty.go
is as follows:
Get hands-on with 1400+ tech skills courses.