Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the equality operator and deepEquals in go?

Tags:

go

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?

like image 611
mogronalol Avatar asked Mar 16 '16 18:03

mogronalol


1 Answers

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.

like image 112
Elwinar Avatar answered Sep 18 '22 23:09

Elwinar