Wednesday, May 20, 2015

non-trivial encoding with golang

Copying struct data from one golang structure to another is pretty simple depending on the variety of structs.
  • create your function similar to Copy(s, d, interface{})
  • at the top of the function check that the parameters are pointers
  • depending on your strategy you might use tags or common field names as the constraint
  • iterate over the structfields and copy the data
  • you might have to validate the types while copying
I've implemented this a few times myself. Custom for each occasion but I would really like a more general solution. Meaning that while the above is mechanical sometimes the data needs to be transformed and there is no simple mechanism for that. 

Ideally it would look something like a sed replace formula. In my latest implementation I used embedded tcl that I had previously incorporated in goose. This time I added a tag called macro and provided the tcl name to execute. This initial implementation is weak because tcl returns strings only; which creates a number of challenges for a more generic solution.

PS: My tag was named macro but I think callback might have been stronger even though I have javascript nightmares at the thought. The again; skip the tag and expand on the reflection. When the copy() function is processing the reflection, look for a named transformation method and execute it. This way I don't have to implement the function and assign it's usage.

UPDATE: I have added/created a project named transcode. It does a good job of copying data between structures.

No comments:

Post a Comment

Fire OS and Android

The relationship between Amazon's FireOS and Google's Android OS is probably very complicated. And while there is probably some very...