0
package main

import (
    "fmt"
)

func main() {
    a := new(struct{})
    b := new(struct{})
    println(a, b, a==b)

    c := new(struct{})
    d := new(struct{})
    fmt.Println(c, d, c==d)
}

output:

0xc000107f37 0xc000107f37 false
&{} &{} true

And, I will get different results after disabling compiler optimization.

0xc000087e4e 0xc000087e4e true
&{} &{} true

Why does the Go compiler do this optimization?

See [this line in the runtime source code ]

(https://github.com/golang/go/blob/6317adeed7815ad335e2e97c463a7c3c4d82fc19/src/runtime/malloc.go#L586)

    if size == 0 {
        return unsafe.Pointer(&zerobase)
    }

I think that since all zero-size variables will be allocated with zerobase, it should print true instead of false.

fguby
  • 21
  • 4
  • 5
    There's no need to allocate space for a value with zero size. The [specification says](https://golang.org/ref/spec#Size_and_alignment_guarantees): *Two distinct zero-size variables may have the same address in memory.* See [1](https://stackoverflow.com/questions/48052722/addresses-of-slices-of-empty-structs), [2](https://stackoverflow.com/questions/52421103/why-struct-arrays-comparing-has-different-result?noredirect=1&lq=1) – Charlie Tumahai May 29 '20 at 03:09
  • @CeriseLimón - The question is why does `a==b` print `false` with optimizations – slebetman May 29 '20 at 04:14
  • 2
    From the spec: "Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables **may or may not** be equal." (emphasize mine). The compiler is free to report true or false and takes this liberty to do so. – Volker May 29 '20 at 05:33
  • @slebetman It looks like the optimizer replaced the call to the allocation function with inline code and that inline code does not use `zerobase`. – Charlie Tumahai May 29 '20 at 10:42
  • @CeriseLimón Then that's the answer. Actually I think Volker's comment is the actual answer and the inline thing explains why it happens. The key is the spec says "may have" instead of "will have" – slebetman May 29 '20 at 12:18
  • See related question [Go lang empty struct confusing feature](https://stackoverflow.com/questions/62155916/go-lang-empty-struct-confusing-feature). – Charlie Tumahai Jun 02 '20 at 15:56

0 Answers0