2 ms·
> There's no great quote to pull from the article, but there's a strong implication that Go has to compare every field in order to determine equality... but thi
by throwaway894345 6y ago
> There's no great quote to pull from the article, but there's a strong implication that Go has to compare every field in order to determine equality... but this simply isn't true. Go only has to do this to determine inequality. If you have two pointers, Go will first check whether the pointers are equal. If they are equal, its job is done. Otherwise, it dives into the fields to see whether those are equal or not. Unless you want "reference equality" to mean that you can just cheaply compare the pointers without falling back to structural equality, but... why would you want to do that?
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 https://play.golang.org/p/zrtTLB6Y9w3
- coder543 6y agoAh, thanks for pointing this out. You're entirely correct. 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 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.