英文:
What is the difference between the equality operator and deepEquals in go?
问题
在阅读了规范之后,我得到了以下理解:
如果结构体的所有字段都是可比较的,那么结构体值也是可比较的。如果两个结构体值的对应非空字段相等,那么这两个结构体值相等。
这对我来说意味着,如果执行 structA == structB
,那么结构体中每个非空字段的值都会应用 fieldA == fieldB
。那么为什么我们还需要深度相等的概念呢?因为如果结构体中的字段也是结构体,根据提供的信息,我理解这些字段也将使用 ==
进行相等性检查,所以肯定会触发对对象图的遍历。
英文:
After reading the spec, I have got:
> Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
This implies to me that doing structA == structB
would mean that the values of each non-blank field in the struct would have fieldA == fieldB
applied to it. So why do we need a concept of a deep equals? Because if the struct has fields which are also structs, the information provided implies to me that those fields will be checked for equality using ==
also, so surely that would trigger traversal down the object graph anyway?
答案1
得分: 8
你所缺少的是指针。在对指针进行==
比较时,应该检查指针值(两个内存地址)还是指向的值(两个变量)?那么在比较切片或映射(两者都可以看作是由指针构成的结构体)时呢?
Golang的作者决定使用==
运算符进行严格比较,并为那些想要比较切片内容的人提供了reflect.DeepEqual
方法。
在测试中,我个人广泛使用reflect.DeepEquals
,因为函数的输出值可能是一个指针,但我真正想要比较的是输出值的内容。
英文:
The thing that you are missing is pointers. When doing a ==
on pointer, should you check the pointer value (two memory addresses) or the pointed value (two vars) ? And when comparing slices, or maps (both of which can be assimilated to a struct made of pointers) ?
The decision of golang's authors was to do a strict comparison with the ==
operator, and to provide the reflect.DeepEqual
method for those that want to compare the content of their slices.
I personnally make an extensive use of reflect.DeepEquals
in tests, as the output value of a function may be a pointer, but waht I really want to compare is the content of the output value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论