简体   繁体   English

golang DeepEqual:当接口映射的值类型为数组时,DeepEqual无效

[英]golang DeepEqual: when the type of value of interface map is array, the DeepEqual is invalidation

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    nodeArray := map[string]interface{}{
        "meta": map[string]interface{}{
            "category": "paragraph"}, "content": []string{"111"}}
    // content is number as 111 or array

    b, _ := json.Marshal(&nodeArray)
    var nodeArrayTest map[string]interface{}
    json.Unmarshal(b, &nodeArrayTest)
    if !reflect.DeepEqual(nodeArray, nodeArrayTest) {
        fmt.Println("!!!! odeArray and nodeArrayTest should be equal")
    } else {
        fmt.Println("odeArray and nodeArrayTest equal")
    }
}

Why when the interface map has array(content is number as 111 or array), the return of DeepEqual is false? 为什么当接口映射具有array(内容为数字或111的数组)时,DeepEqual的返回为false? And when the content value is a string, a map, the DeepEqual is true. 当内容值为字符串,映射时,则DeepEqual为true。

Printing out the two values, in question, we can see that they are different: 打印出这两个值,我们可以看到它们是不同的:

nodeArray = map[string]interface {}{"meta":map[string]interface {}{"category":"paragraph"}, "content":[]string{"111"}}
nodeArrayTest = map[string]interface {}{"content":[]interface {}{"111"}, "meta":map[string]interface {}{"category":"paragraph"}}

In particular, nodeArray["content"] is a []string slice, while nodeArrayTest["content"] is aa []interface{} slice. 特别是, nodeArray["content"][]string切片,而nodeArrayTest["content"][]interface{}切片。 The reflect.DeepEqual function does not consider these equal due to the type mismatch. 由于类型不匹配, reflect.DeepEqual函数认为这些不相等。

The encoding/json module decodes into an []interface{} slice because JSON arrays can contain values of different types. 由于JSON数组可以包含不同类型的值,所以encoding/json模块解码为[]interface{}切片。

aaa := map[string]interface {}{"meta":map[string]interface {}{"category":"paragraph"}, "content":[]string{"111","222"}}
bbb := map[string]interface {}{"content":[]string{"222","111"}, "meta":map[string]interface {}{"category":"paragraph"}}

It's not true. 这不是真的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM