英文:
golang DeepEqual: when the type of value of interface map is array, the DeepEqual is invalidation
问题
当接口映射中的数组(content为数字111或数组)时,为什么DeepEqual的返回值是false?而当content的值为字符串或映射时,DeepEqual的返回值是true。
英文:
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? And when the content value is a string, a map, the DeepEqual is true.
答案1
得分: 3
打印出这两个值,我们可以看到它们是不同的:
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"}}
特别地,nodeArray["content"]
是一个 []string
切片,而 nodeArrayTest["content"]
是一个 []interface{}
切片。由于类型不匹配,reflect.DeepEqual
函数认为它们不相等。
encoding/json
模块将解码为 []interface{}
切片,因为 JSON 数组可以包含不同类型的值。
英文:
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 a a []interface{}
slice. The reflect.DeepEqual
function does not consider these equal due to the type mismatch.
The encoding/json
module decodes into an []interface{}
slice because JSON arrays can contain values of different types.
答案2
得分: -2
aaa := map[string]interface {}{"meta":map[string]interface {}{"category":"段落"}, "content":[]string{"111","222"}}
bbb := map[string]interface {}{"content":[]string{"222","111"}, "meta":map[string]interface {}{"category":"段落"}}
这是不正确的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论