Promoted fields - using name when initialization struct

709 views
Skip to first unread message

Hubert Kr

unread,
Dec 10, 2015, 11:21:26 AM12/10/15
to golang-dev
Hi,

Can anyone give me some insight as to the design decision behind why you can't create a struct literal with direct references to embedded struct members?

Here is example how it could work: http://play.golang.org/p/XS3fiCY-BH

Has approach changed since than? Go still doesn't allow to use fields name in composite literals of the struct? Maybe it's time to change it?

Hubert Krauze

minux

unread,
Dec 10, 2015, 8:42:41 PM12/10/15
to Hubert Kr, golang-dev
No, it hasn't been changed since Go 1.

I think  one reason not to allow direct initialization of fields of anonymous
embedded structs is the embedded struct pointer case. It should not hide
the fact that a new struct is allocated separately.

E.g.
type PacketPtr struct {
*Header
Data      string
ExtraData string
}

var x = PacketPtr{Header: &Header{ ... }, Data: "", ExtraData: "" }

Robert Griesemer

unread,
Dec 11, 2015, 12:21:28 AM12/11/15
to minux, Hubert Kr, golang-dev
This is a question that has come a few times before.

I admit that I often wished myself that I would be possible.

Minux has a good point: what to do if there are embedded pointer types?

(There's an obvious way out: it would simply be invalid to use direct reference that requires an indirection. But there's more: what if the direct reference is ambiguous? As with explicit selectors, that would also be invalid.)

In summary: It probably could be made to work w/o too much trouble; but I haven't through through all the details - and there's always details. There's also a question of readability and whether it is really worth making the language more complex.

There is always the proposal process - but as has been pointed out before: The bar for language changes is very high.

- gri

--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages