Could (known) type names be removed from complex struct literals?

143 views
Skip to first unread message

mjy

unread,
May 22, 2013, 10:23:37 AM5/22/13
to golan...@googlegroups.com
Hi,

struct literals often seem to be the most practical way to initialize objects, but in Go they require type names even in places where the types are already known. Could these type names not be omitted?

package main

type Foo struct {
    A []string
    B []string
}

func moo(f ...Foo) {
}

func main() {
    // ideally: moo({A: {"1","2"}}, {B: {"x","y"}})
    moo(Foo{A: []string{"1","2"}}, Foo{B: []string{"x","y"}})
}

Similarly for various other situations:

package main

var m map[string]bool

func main() {
    // why not: m = {} ?
    m = map[string]bool{}
}

If this is obvious to everyone else / a FAQ etc. I apologize. ;-)

peterGo

unread,
May 22, 2013, 11:30:55 AM5/22/13
to golan...@googlegroups.com
mjy,

Search golang-nuts for several discussions of this issue.

For example,

"We aren't allowing struct literals to elide the types, at least not yet, because elision can cause subtle bugs as programs evolve. Unlike in a slice, the fields of a struct can be rearranged, and the types provide more information about correctness than the values themselves.  Such rearrangement could introduce subtle bugs that would be hard to discover, especially in a large program.   Thus the elision is not permitted for structs at the moment." -rob

https://groups.google.com/d/msg/golang-nuts/6jJButs4ivQ/nfcg8vmaM0wJ

Peter

John Nagle

unread,
May 22, 2013, 11:28:18 PM5/22/13
to golan...@googlegroups.com
On 5/22/2013 8:30 AM, peterGo wrote:
> mjy,
>
> Search golang-nuts for several discussions of this issue.
>
> For example,
>
> "We aren't allowing struct literals to elide the types, at least not yet,
> because elision can cause subtle bugs as programs evolve. Unlike in a
> slice, the fields of a struct can be rearranged...

That's a good argument for named initialization.

It makes sense for Go, because Go has default
initialization values. So, for example, you could
initialize the public members of a struct while letting
the private ones default.

John Nagle

roger peppe

unread,
May 23, 2013, 11:01:16 AM5/23/13
to golang-nuts
For more context around the subject of this thread, see
https://groups.google.com/forum/?fromgroups#!topic/golang-dev/aWw7b-_FCF8
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
Reply all
Reply to author
Forward
0 new messages