I have a map where I have stored different struct types and I want to retrieve them to know what type of struct I have to do the unmashal.
When the value of the key is directly the struct that I need, it works. But if I use another struct, it doesn't.
type typeStruct struct {
typeValue interface{}
}
type typeA struct {
Value string `json:"value"`
}
var types1 map[string]typeA = map[string]typeA{
"typeA": typeA{},
}
var types2 map[string]typeStruct = map[string]typeStruct{
"typeA": typeStruct{typeValue: typeA{}},
}
func main() {
jsonString := `{
"value": "value1"
}`
//this behaves as expected
resultType1 := types1["typeA"]
fmt.Println(fmt.Sprintf("type1: %T", resultType1)) //prints: type1: main.typeA
json.Unmarshal([]byte(jsonString), &resultType1)
fmt.Println(fmt.Sprintf("type1: %T", resultType1)) //prints: type1: main.typeA
fmt.Println(resultType1) //prints: {value1}
//Not this, the type is map[string]interface instead of main.typeA
resultType2 := types2["typeA"].typeValue
fmt.Println(fmt.Sprintf("
type2: %T", resultType2)) //prints: type2: main.typeA
json.Unmarshal([]byte(jsonString), &resultType2)
fmt.Println(fmt.Sprintf("type2: %T", resultType2)) //prints: type2: map[string]interface {}
fmt.Println(resultType2) //prints: map[value:value1]
}
Go Playground link
Do you know what is happening? And how can I make it work properly?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…