Richard Bucker

non-trivial encoding with golang

Posted at — May 20, 2015

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 pointersdepending on your strategy you might use tags or common field names as the constraintiterate over the structfields and copy the datayou might have to validate the types while copyingI’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.