Literal assignment for array of anonymous struct

7,252 views
Skip to first unread message

Hans Stimer

unread,
Oct 20, 2010, 2:47:37 PM10/20/10
to golang-nuts
How do you do a literal assignment with an array of anonymous structs?

type Foo struct {
a int
b []struct{c, d int}
}

var foo = Foo{1, []struct{{2, 3}, {4, 6} } // !!! Compile error

Evan Shaw

unread,
Oct 20, 2010, 2:53:04 PM10/20/10
to Hans Stimer, golang-nuts

It ends up being verbose and repetitive.

var foo = Foo{1, []struct{c, d int}{
struct{c, d int}{2, 3},
struct{c, d int}{4, 6},
}}

In this case, I'd say it's better just to name the struct.

- Evan

Hans Stimer

unread,
Oct 20, 2010, 3:17:12 PM10/20/10
to golang-nuts
Thanks Evan, I was trying to redeclare the struct just once for all
the array elements and I couldn't find a way that worked.

I wonder how this feature meets the standard for "make programmers
more productive".

Thanks Evan.

On Oct 20, 11:53 am, Evan Shaw <chicken...@gmail.com> wrote:

John Asmuth

unread,
Oct 20, 2010, 3:31:38 PM10/20/10
to golang-nuts
Productivity is not measured in keystrokes.

roger peppe

unread,
Oct 20, 2010, 3:32:18 PM10/20/10
to Evan Shaw, Hans Stimer, golang-nuts
this would become much less repetitive if some changes
that have been recently suggested by the go authors
get made.

Russ Cox

unread,
Oct 20, 2010, 5:06:47 PM10/20/10
to Hans Stimer, golang-nuts
On Wed, Oct 20, 2010 at 15:17, Hans Stimer <hans....@gmail.com> wrote:
> Thanks Evan, I was trying to redeclare the struct just once for all
> the array elements and I couldn't find a way that worked.
>
> I wonder how this feature meets the standard for "make programmers
> more productive".

There was a long thread about composite literal notation
in the last few weeks. I suggest finding it and reading it.
Rob made the point that things that make sense in
tiny gems may not make sense at scale for very large
programs. It remains to be seen if this specific case
is one of them, but it was part of the discussion.

Russ

Andrew Gerrand

unread,
Oct 20, 2010, 8:11:39 PM10/20/10
to r...@golang.org, Hans Stimer, golang-nuts
Reply all
Reply to author
Forward
0 new messages