Convert map[string]interface{} to Struct as Generic Function in Go

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.

[Read More]
go 

Error Handling in Go

Error As Value

Error is treated as value in Go. No try/catch, but there is panic/recover. Other programming languages is using try/catch for regular error, while Go use panic/recover for fatal or unrecoverable condition such as nil pointer dereference and so on. Hence, panic/recover is not a direct replacement for try/catch.

For regular error, we need to return it like we return a variable. Some people are alright with this decision, but some are not because it makes the code verbose and you will find if err != nil are everywhere.

[Read More]
go