Go: cmd/compile: empty struct addresses are not equal

Created on 8 Jan 2018  路  7Comments  路  Source: golang/go

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

go version go1.9.2 linux/amd64

Does this issue reproduce with the latest release?

Yes.

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN="/vagrant/gopath/bin"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/vagrant/gopath"
GORACE=""
GOROOT="/vagrant/go"
GOTOOLDIR="/vagrant/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build779422972=/tmp/go-build"
CXX="g++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"

What did you do?

var a, b struct{}
fmt.Println(&a == &b) // true

code link: https://play.golang.org/p/zUnW3LHCCbi.

What did you expect to see?

Print true.

What did you see instead?

Print false. Go with version 1.3.3 prints true but 1.9 print false. Is this reasonable or a bug?

FrozenDueToAge NeedsInvestigation

Most helpful comment

@mvdan the OPs example prints true in previous versions of Go. They want to know if this change was intentional, or a bug.

All 7 comments

You are comparing addresses of empty structs. If you compare values, then it returns true.
Try
fmt.Println(a == b) // true

@mvdan the OPs example prints true in previous versions of Go. They want to know if this change was intentional, or a bug.

I did not get that impression from reading the post, my apologies.

The title is misleading. You're not comparing empty structs, you are comparing the addresses of two struct{} variables.

Also your expectations are incorrect. The two addresses does not need to be equal. The spec says:

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

So both true and false are correct answers.

I'd argue that it doesn't really matter whether the change (which btw was introduced in go1.6, the first version that prints false) was introduced intentionally or as a side effect of new optimizations in the compiler, since both answers are allowed by the spec, but I'm labelling this as needsInvestigation in case there's actually something unexpected going on.

Two distinct zero-size variables may have the same address in memory.
https://golang.org/ref/spec#Size_and_alignment_guarantees

Yes, this is working as intended per the spec, as others have pointed out.

Was this page helpful?
0 / 5 - 0 ratings