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

huangapple go评论68阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年3月18日 11:39:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/22469917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定