dimanche 17 mai 2020

Go map struct type conversion after json unmarshaling

I'm trying to create a factory pattern of sorts in Go, but not having any luck. I wanted to be able to use reflection, kind of in the way other languages do it, to create objects/structs on the fly with the object name. However, go doesn't seem to support it the way I hoped, and so I've opted for a simpler approach (see below) by just mapping the struct to a string using a map.

The issue I've now run into, is that, it initially seems to work based on my testing, however, once I call json.Unmarshal on it, it goes from the correct struct type, to a map[string]interface{}, as if it's almost reverting to the containing object's type?

st := make(map[string]interface{})
st["StructName1"] = s.StructName1{}
st["StructName2"] = s.StructName2{}
//...

fmt.Printf("1) '%+v' '%+v'\n", reflect.ValueOf(st["StructName1"]), reflect.TypeOf(st["StructName1"]))
fmt.Printf("2) '%+v' '%+v'\n", reflect.ValueOf(s.StructName1{}), reflect.TypeOf(s.StructName1{}))

ff := st["StructName1"]
err := json.Unmarshal([]byte(reqBody), &ff)
fmt.Printf("3) '%+v' '%+v'\n", reflect.ValueOf(ff), reflect.TypeOf(ff))

Output:

1) '{V1: V2:{V2v1: V2v2: V2v3:}}' 'structs.StructName1'
2) '{V1: V2:{V2v1: V2v2: V2v3:}}' 'structs.StructName1'

3) 'map[V2:map[V2v1:value1 V2v2:value2 V2v3:value3] V1:"value4"]' 'map[string]interface {}'

Unmarshaling 'succeeds', in that it has no errors, but the type that is printed in 3) is a map[string]interface{}. Any ideas why this is?

Also, assigning ff the struct directly instead of using a map, i.e.

ff := s.StructName1{}

Works completely fine.

Also, if you have any advice on a better approach for this in go, I'd appreciate any input.

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire