0

I have the following code:

package main

import "fmt"

type MyStruct struct {
}

func main() {
    a := &MyStruct{}
    b := &MyStruct{}

    fmt.Println(a == b)
    fmt.Println(*a == *b)
}

Which as expected outputs

false
true

But, if I add two Print statements at the end like this:

package main

import "fmt"

type MyStruct struct {

}

func main() {
   a := &MyStruct{}
   b := &MyStruct{}

   fmt.Println(a == b)
   fmt.Println(*a == *b)
   fmt.Println(&a)
   fmt.Println(&b)
}

The output becomes something I did not expect:

true
true
0xc0000ae018
0xc0000ae020

Why does it become true in the first case?

naneri
  • 3,771
  • 2
  • 29
  • 53
  • 2
    This is only because you're using a **zero-sized struct** (it has no non-zero-sized fields). Two distinct a zero-sized structs (or two distinct zero-sized arrays) **MAY** have the same memory address, i.e. `a == b` MAY be true, it's not guaranteed, but it can happen. With non-zero struct this is guaranteed to never happen: https://go.dev/play/p/0i8DRmBwz1R – mkopriva Dec 10 '22 at 06:37
  • 1
    Go all the way to the bottom of the [spec](https://go.dev/ref/spec), it's literally the last paragraph. – mkopriva Dec 10 '22 at 06:38
  • 1
    https://stackoverflow.com/questions/26378995/why-two-pointer-of-same-struct-which-only-used-new-function-for-creating-compare and https://stackoverflow.com/questions/25734504/different-pointers-are-equal and you're bound to find more if you search. – mkopriva Dec 10 '22 at 06:47

1 Answers1

3

From the Go language specification:

Pointers to distinct zero-size variables may or may not be equal.

MyStruct is struct{}, which is a zero-size type. Hence, a == b may be true or false.

Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33