Image for post
Image for post

Golang slice append gotcha

Tomasz Pietrek
Feb 11, 2016 · 2 min read

Slices in Go are very convenient way to deal with dynamic arrays. However, they don’t always behave as one may expect.

TL;DR: here is link to SO question describing problem and solution.

I guess that if you’re reading this, you’re already somehow familiar with Go, so I won’t introduce it in any way and I’ll focus on slices only.

Slices in Go are very useful Go’s arrays abstraction. Both slices and arrays have typed value, but arrays have also defined static length, therefore they’re usually not that useful, as You can’t append to them, cut them and in general — manipulate use them in friendly way. What arrays lack (by design) is provided by slices.

One of the most used method is build-in append function:

As first argument it takes slice we want append to and as second — element we want to be appended. It doesn’t modify the slice provided as first argument. Instead, it returns new slice.

Looks easy, right?
But there is one gotcha:

You can run this example here and see, that the sliceFromLoop will print always last value appended to it!

Why all previous new slices returned by append function are modified by last append?

Because Go append mechanic manipulates underlying array all the time and all new slices and their values are based on that array too.

That means, that creating new slice variables based on append mechanic can lead to very hard to discover bugs and problems.

What’s the solution?

someSlice = append(someSlice, newElement)
func copyAndAppend(i []int, vals []int {
j := make([]int, len(i), len(i)+len(vals))
copy(j, i)
return append(j, vals...)

or to just create a shallow copy of old slice:

newSlice := append(T(nil), oldSlice...)

It’s not very often used pattern. I found that problem after few years of writing production code in Go and probably that’s why it’s even more confusing and frustrating.

More info about slices:
very useful website about Go’s gotchas, including mentioned one

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store