-5

Code:

func main(){
    var (
        a struct{}
        b struct{}
    )
    println("&a:", &a)
    println("&b:", &b)
    println("&a == &b:", &a == &b)
    m := &a
    n := &b
    println("m == n:", m == n)

    x := make([]struct{}, 10)
    println("&x[0] == &x[1]:", &x[0] == &x[1])
}
Result:  
PS D:\emptyStruct> go run -gcflags '-m -N -l' main.go  
./main.go:15:11: make([]struct {}, 10) does not escape
&a: 0xc00004ff05  
&b: 0xc00004ff05  
&a == &b: false  
m == n: true  
&x[0] == &x[1]: true  

Who can explain why the address of "&a" and "&b" is the same, but the "==" operator judges them to be false?

I believe that the addresses of all empty structs are the same, just like the x slice above, where the addresses of each element are the same, and this is fine, but I really cannot understand why the addresses printed by "&a" and "&b" are the same, but the "==" operator judges them to be false.

3

1 Answer 1

1
  • Even though &a and &b print the same address, the compiler treats them as distinct addresses for the purpose of comparison. This is why &a == &b returns false.
  • When you assign &a to m and &b to n, both m and n point to the same memory address. Thus, m == n returns true because they are both pointers to the same location.

Not the answer you're looking for? Browse other questions tagged or ask your own question.