On Fri, Aug 4, 2023 at 8:08 AM Nate Finch <nate.fi...@gmail.com> wrote:
>
> If I have a struct
>
> type User struct {
>     Name string
>     ID int
> }
>
> type Group struct {
>      Leader  User
> }
>
> Why is it that the go tool can't infer what type I'm constructing for the 
> Leader field here?
>
> g := Group{
>     Leader: {
>            Name: "Jamie",
>            ID: 5,
>     },
> }
>
> Cleary, the compiler knows I'm constructing a variable of type Group, and 
> thus should know that Leader: is a field in Group, and thus what type I am 
> constructing to assign to that field.  It's not like it's an interface where 
> I could be assigning anything.
>
> Finally, why does this work with maps, but not struct fields?
>
> users := map[string]User {
>     "Jamie" : {
>            Name: "Jamie",
>            ID: 5,
>      },
> }
>
> This works and feels almost identical to the Group code above. Define the 
> enclosing type, and then the subtype is obvious and thus implicit.
>
> I presume this is some parser thing where it can't distinguish between two 
> possible valid constructions, though I can't think of exactly what other 
> construction it might mean....

I think this is https://go.dev/issue/12854.  At least that is related.

The reason we don't do it today boils down to: we implemented it in
gofmt -s and weren't really happy with how it looked.  A number of
existing composite literals became nearly unreadable when the types
were omitted.  They were just collections of braces and elements, and
it was hard to tell what they meant.  That was a long time ago and we
may feel differently now, if somebody wants to seriously investigate.

Ian

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcVTbE%3DxqDDO64d5ZOXD7VgOcNf0WzZzNP5T_esJ6HTP1Q%40mail.gmail.com.

Reply via email to