Here’s a feature request for Go: shamelessly copying JavaScript and adding support for the “rest” operator in literals. Go does have a rest operator, but it only works in function calls. I was writing a unit test today and I was thinking to myself that it would be nice to use this operator in both slice and struct literals as well.

This could be useful for making copies of values without modifying the originals. Imagine the following bit of code:

type Vector struct { X, Y, Z int }
oldInts := []int{3, 4}
oldVec := Vector{X: 1}

newInts := append([]int{1, 2}, oldInts...)
newVec := oldVec
newVec.Y = 2
newVec.Z = 3

Now imagine how it would look if rest operators in literals were supported:

type Vector struct { X, Y, Z int }
oldInts := []int{3, 4}
oldVec := Vector{X: 1}

newInts := []int{1, 2, oldInts...}
newVec := Vector{Y: 2, Z: 3, oldVec...}

I hope you’ll agree that it looks a bit neater than the former. Certainly it looks more pleasing to my eyes. True, this is a contrived example, but the code I’m writing for real is not too far off from this.

On the other hand, Go does prefer clarity over brevity; and I have seen some JavaScript codebases which use these “rest” operators to an absurd level, making the code terribly hard to read. But I think the Go user-base is pretty good at moderating themselves, and just because it could result in unreadable code, doesn’t make it a forgone conclusion. Just look at Go’s use of type parameters.

Anyway, if the Go team is looking for things to do, here’s one.