-3

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)
}
nirvana
  • 1
  • 1

1 Answers1

-1

Type assertion tests the declared type of an object. In this code, abc is of type MyType, but the nested objects in abc are map[string]interface{} instances. Thus, you cannot type-assert that to MyType, but you can convert it:

def := MyType(abc["def"].(map[string]interface{}))
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59