相等运算符(`==`)和 `deepEquals` 在 Go 语言中有什么区别?

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

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.

huangapple
  • 本文由 发表于 2016年3月17日 02:05:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/36043575.html
匿名

发表评论

匿名网友

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

确定