golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.55k stars 17.61k forks source link

spec: Embedded structs opposed situation #20972

Closed OmidHekayati closed 7 years ago

OmidHekayati commented 7 years ago

Please answer these questions before submitting your issue. Thanks!

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

go version go1.8 linux/amd64

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

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

What did you do?

We have 3 type:

type A struct {
    B
    C
}
type B struct {
    x int
    y string
}
type C struct {
    z string
}

because we can use this model of that type

var a A
a.x = 0

It is very obvious that type B & C embed in A, like we have this in real situation:

type A struct {
    x int
    y string
    z string
}

What did you expect to see?

We expect to see that this would work!

a := A{x: 2}

What did you see instead?

But get this compile error

unknown field 'x' in struct literal of type A

Why Go has this opposed situation? It is very bad we must think differently for same thing!

https://play.golang.org/p/uM5JkO5EvE

bradfitz commented 7 years ago

For questions about Go, see https://golang.org/wiki/Questions.