Being able to encode our data and decode it back again intact is an important part of transmitting data between different services. Go provides encoders for XML, JSON and even a fast binary encoder.

JSON is an obvious choice for various reasons, it has a very simple syntax that almost all languages can understand, the only downside to this is that is a bit slow compared to binary encoders like encoding/gob.

But there’s one thing that encoding/gob doesn’t give you, which is portability, what if you want to send your data through RabbitMQ to a Node.js or Elixir backend? Well good luck because it won’t know how to decode your data.

What if I don’t know the type at compile time?

Now let’s say you’re building a library that does some kind of message passing and expect to be encoding and decoding arbitrary types.

If you’re retrieving a JSON document and need to decode data without knowing the type before hand, you can use reflection to decode it into your data type using a type safe manner.

The first thing that we need to do is be able to get a reflect.Type from it’s string representation, a simple way to do that is to maintain a map[string]reflect.Type with all the types that you need to decode.

Everytime you encode a type or you have access to the type, it can be registered in the map: