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.
struct{}
) may have the same address in memory; in the spec, which explains why the actual address (the unsafe pointer) is the same, though the objects as far as the go runtime is concerned are distinct. I did a quick search and found that Dave Cheney mentioned the same thing, IMO implying that 0-byte objects internally can point to a single (special) address