append() gotcha!

271 views
Skip to first unread message

DrGo

unread,
Aug 15, 2017, 10:53:16 PM8/15/17
to golang-nuts
Hello,

The following compiles as well as evades scrutiny by go Vet (and many a human reviewer) resulting in perplexing bugs. What purpose calling append() with only one argument serves? Shouldn't it be banned?


```
var byteArray= []byte{'A', 'B',}

func main() {
buf:=[]byte {'C'}
buf = append(byteArray)  //<--- gotche meant: buf = append(buf, byteArray)
fmt.Println(string(buf))
}
```

Nate Finch

unread,
Aug 15, 2017, 11:16:45 PM8/15/17
to golang-nuts
This is an unfortunate side effect of using ... (a variadic) in append.  Zero is a valid number of arguments to pass to it.

However, I think this is a 100% valid thing to put into go vet.  There's never a time when someone writes this code on purpose instead of just writing buf = byteArray.

Val

unread,
Aug 16, 2017, 9:09:37 AM8/16/17
to golang-nuts
Agreed, append with only one argument doesn't look good and should be vetted.

As a superset of this problem, any use of
  a = append(b, c)
with b != a (i.e. not assigning back to the same slice variable) 
looks either broken or cryptic me.
This holds whether c is zero or one or more variadic elements.
I mean, while there are a few usages where it is written on purpose, it makes reading and reasoning much more difficult.
Val

Nate Finch

unread,
Aug 16, 2017, 3:31:13 PM8/16/17
to golang-nuts
Wrote it up as an issue: https://github.com/golang/go/issues/21482

and I agree that using append to assign to a different variable than the one in the append call is almost always going cause surprising behavior.... but it's less clearly a mistake than append with only a single argument.

xingtao zhao

unread,
Aug 16, 2017, 5:24:12 PM8/16/17
to golang-nuts
Sometimes, I use:
a := []int{ 1, 2, 3 }
b : = append([]int(nil), a...)

to copy a slice.

Lucio

unread,
Aug 16, 2017, 11:49:15 PM8/16/17
to golang-nuts


On Wednesday, 16 August 2017 05:16:45 UTC+2, Nate Finch wrote:
This is an unfortunate side effect of using ... (a variadic) in append.  Zero is a valid number of arguments to pass to it.


But append is not a normal function, it is an intrinsic, so the compiler could implement a check? It would have to be an error to have a single argument, which I presume would be acceptable? Are there likely to be buggy programs out there that would break if it did?

Lucio. 

DrGo

unread,
Aug 20, 2017, 12:35:40 AM8/20/17
to golang-nuts
Thanks Nate,

Reply all
Reply to author
Forward
0 new messages