Motivation
I developed a pattern for Unmarshalling JSON that has keys with multiple possible value types.
I know, they are a PITA but when it is from an API you do not control, what can you do other than mitigate the problems on your side.
Say you have something that has 3 different types, I want to unmarshall to a different interface depending on the type, and that interface can just delegate to the native map[string]interface{}
Did this once already in Java and it works a charm!
I wrote an immutable object library for Java that used a Map<String,Object>
as a delegate to an interface
that used Dynamic Proxy
to route the calls to the delegated map. The neat thing about this was I got a very nice “versioned” immutable object implementation for very little effort.
This allowed me to use Interfaces
that delegated to Map<String,Object>
and switch out the interfaces at runtime to supply the correct semantic.
This is just a single part of the library I wrote, but it is the core piece of it. Fairly straight forward.
“Mutations” created sparse maps that delegated to the previous map.
Interface method names were keys into the map and returned values, if they did not exist it just searched in the nested maps until it found a key.
t think I have made a pretty comprehensive search and have not found anything that does this same thing in Go. I could be wrong.
I am looking to go the equivalent in Go and see how it could be done with an Interface
and a map[string]interface{}
as well, as I “port” a pretty substantial code base that I am very familiar with from Java to Go.
Before I go and reimplement this particular wheel I wanted to see if anyone had already done something like this before me.