Hello,
I'm looking for a way to insert an extract data dynamically from structs in Go. To better undestanding, this is my scenario. I need 2 functions:
func Build(name string, slice []interface{}) (Data, error)
: wherename
is a object type identifier andslice
is a list of values. This function must create an object that represents the typename
and populate it with values formslice
, and it must use the order tag to do this job.func Extract(name string, data Data) ([]interface{}, error)
: wherename
is a object type identifier anddata
is a struct pointer. This function must create slice ofinterface{}
with the values from the fields of the objectdata
, again using order tag to set value order.
I need to create those two function in a generic way because I have 44 diferent structs (generated by Apache's Thrift Go implementation). I wanna avoid to code 88 functions, 2 for each object.
I'm playing with reflect
package and done a lot of progress. See my main.go
file. I'm having 3 problems with my code:
- My Build function return a
reflect.Value
object, I wanna convert it to*ObjectType
, where ObjectType is retrieved inside the function. - In Build function,
slice
will have int values as uint64 (because a default untyped conversion from a json string). I need to convert those values to the right type, as defined in the fields ofObjectType
. - If I pass the object returned from a Build function to the Extract function I will get errors on the
.Elem()
from line 50. I suspect that this is caused by problem 1, but I may be wrong.
I know I can solve convertion problems with a switch clause using Kind
values. But, if possible, I wanna avoid it.
So, you guys know any way to solve those problems, or any better soluction to achiev it?
Thank you