Why is type inference still so rudimentary?

151 views
Skip to first unread message

Nate Finch

unread,
Aug 4, 2023, 3:08:24 PM8/4/23
to golang-nuts
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....

Ian Lance Taylor

unread,
Aug 4, 2023, 5:39:52 PM8/4/23
to Nate Finch, golang-nuts
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

jimmy frasche

unread,
Aug 4, 2023, 6:16:43 PM8/4/23
to Ian Lance Taylor, Nate Finch, golang-nuts
I wish there were more cases where the types could be elided. Always
leaving it off would be a bad idea but how much to put in should be at
the author's discretion. There are times when it clarifies but more
times when it just adds extra steps. I know that the current rules
have justifications but they still feel entirely arbitrary and it's
getting to be one of the more annoying aspects of reading and writing
Go (because most everything else has been addressed!)
> --
> 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.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcVTbE%3DxqDDO64d5ZOXD7VgOcNf0WzZzNP5T_esJ6HTP1Q%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages