Go: proposal: short hand syntax for maps and slices

Created on 28 Aug 2019  路  5Comments  路  Source: golang/go

Go has type inference for declaring new variables, however the RHS of the expression must always be a self contained expression whose type can be easily determined from context. However, there exist situations where the type can be inferred from the LHS and RHS of the expression can be made more concise.

In particular, this applies to maps and slices.

I propose that instead of specifying the full type for a map or slice, if the type can be determined from the LHS, then just map or [] can be used.

For example

type SomeWorker struct {
    cache map[string]string
    ident []byte
}

func NewSomeWorker() *SomeWorker {
    return &SomeWorker{
        cache: map{
            "foo": "bar"
        },
        ident: []{1, 2, 3},
    }
}

The primary motivation for this proposal comes from writing table driven tests; I often run into situations where I need to initialise a lot of maps as part of the test case, and writing the type information feels repetitive.

I'm not sure if this concept can be applied to general variable declarations, since it may hurt readability and maybe much hard to implement. For instance, this:

var x = map{
    "foo": "bar",
}
FrozenDueToAge Go2 LanguageChange Proposal

Most helpful comment

Seems to me like https://github.com/golang/go/issues/12854 would be a more generic and better solution to this problem - your solution doesn't cover other kinds of comosite literals, such as structs.

All 5 comments

Seems to me like https://github.com/golang/go/issues/12854 would be a more generic and better solution to this problem - your solution doesn't cover other kinds of comosite literals, such as structs.

didn't know about that proposal, but that was opened 4 years ago and still no action has been taken. Maybe this will help reignite the discussion, or maybe cut down on the scope to make it more feasible.

Language changes take time to be considered properly, and the Go language has only started accepting new features in the past six months. If the proposal hasn't been declined, it could still be accepted.

I still think that it would be better to give your support to that proposal. Two very similar proposals, or a proposal that is a subset of another, have less chance of success than a single popular proposal.

@mvdan fair enough. Should I close this issue?

This isn't identical to #12854, but at least to me #12854 seems more consistent with how other parts of the language work. If you would be OK with the approach described in #12854, then I personally would favor closing this issue in favor of that one.

Was this page helpful?
0 / 5 - 0 ratings