I am puzzled to see why this code is failing.
// This fails with
// panic: interface conversion: interface {} is map[string]interface {}, not main.MyType
// def := (abc.(MyType))["def"]
// But this succeeds
def := (abc.(map[string]interface{}))["def"]
My thinking is type assertion enforced in above logic should also work. Can someone please clarify?
Here is the entire code and also on playground.
Thanks in advance.
func foo() {
type MyType map[string]interface{}
str := `{
"abc": {
"def": {
"mln": true
}
}
}`
var data MyType
if err := json.Unmarshal([]byte(str), &data); err != nil {
fmt.Println(err)
return
}
fmt.Println(data)
abc := data["abc"]
fmt.Println(abc)
// This fails with
// panic: interface conversion: interface {} is map[string]interface {}, not main.MyType
// def := (abc.(MyType))["def"]
// But this succeeds
def := (abc.(map[string]interface{}))["def"]
fmt.Println(def)
}