by throwaway894345 · 6y ago · 0 comments
I might be missing something, but Go definitely doesn't compare every field in order to determine equality or inequality. Go only compares pointers, and it does this because (1) pointers are values and they get compared like values and (2) sometimes you want to do identity comparison and sometimes you want to do value comparison and the language has no way to infer which you intend unless you tell it (and the mechanism for communicating this to the compiler is by the type of of the operands you pass to the equality operator--pointers for identity comparison and values for value comparison).
Here's a little playground link to illustrate: https://play.golang.org/p/zrtTLB6Y9w3
I'm not sure how I got confused with the special case around string comparisons, and forgot that it didn't apply to regular struct pointers. It was late in the evening, so I guess that's my excuse?
BenchmarkSameRef-12 620150179 1.92 ns/op
BenchmarkDiffRef-12 6102709 204 ns/op
Source: https://play.golang.org/p/DbjkstOCZ-Y (although you can't actually run it on the Go playground)Go will check whether two strings have the same underlying pointer first. If the pointers are different, then it compares the contents.
I stand by my earlier statement that I think pure reference equality is just a bad idea 99.9% of the time. I would prefer if Go did deep equality with every comparison when needed the way it does with strings. If you have to use some clunky syntax or built-in function to do just a reference comparison, that would be perfectly fine with me. Unfortunately, Go does exactly what you described.
With a quick google, I didn't immediately find a linter to complain about comparing struct pointers rather than struct values, so maybe I'll write a linter like that sometime if I can find the time and motivation.