-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)
}
0

1 Answer 1

-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{}))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.