There was a similar discussion 
here: https://groups.google.com/g/golang-nuts/c/JBVqWYFdtC4/m/VJC2OLJcAQAJ

It is very sensitive to exactly how the variables are used. For example, if 
you replace your println() with fmt.Println() then you get a different 
answer.
https://go.dev/play/p/D5z4q6iCTke

On Wednesday 19 June 2024 at 17:59:43 UTC+1 Oliver Eikemeier wrote:

> I'm observing some strange behavior and could use some help understanding 
> it.
>
> The specification <https://go.dev/ref/spec#Comparison_operators%E2%80%9D>
>  says: *“Pointers to distinct zero-size variables may or may not be 
> equal.”*
>
> With the following program (Go Playground 
> <https://go.dev/play/p/D41jZhecbyK>):
> var ( a struct{} b struct{} eq = &a == &b ) func f1() { println("&a:", 
> &a) println("&b:", &b) println("&a == &b:", eq) } 
>
>
> I'll get
> &a: 0x537580 &b: 0x537580 &a == &b: false 
>
>
> Okay, a and b are empty structs, do not escape, so they share the same 
> address - fine. Also, some optimizer sees that a and b are different 
> variables, so their addresses must be different, and decides to make &a 
> == &b a constant - wrong, but I can live with that.
>
> My question would be: Is this behavior expected, somehow defined by the 
> specification, or is it undefined behavior?
>
> Let's try to confuse the optimizer a little (Go Playground 
> <https://go.dev/play/p/_r5WEULKPKd>):
> var ( a struct{} b struct{} aa = &a ba = &b eq = aa == ba ) func f1() { 
> println("&a:", aa) println("&b:", ba) println("&a == &b:", eq) } 
>
> results in
> &a: 0x5375a0 &b: 0x5375a0 &a == &b: true 
>
>
> Mission accomplished, too complicated to calculate in advance. But globals 
> are bad, so (Go Playground <https://go.dev/play/p/SleVYsVj3u5>):
> func f2() { var ( a struct{} b struct{} aa = &a ba = &b eq = aa == ba ) 
> println("&a:", aa) println("&b:", ba) println("&a == &b:", eq) } 
>
> &a: 0xc000046740 &b: 0xc000046740 &a == &b: false 
>
>
> Seems like inlining helps generate false answers.
>
> The interesting part here is that I can create two pointers (which may or 
> may not be equal per specification), but depending on how I compare them I 
> get different results.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/192b08fd-888d-47d9-bcb8-d2c71f270a53n%40googlegroups.com.

Reply via email to