Golang slice append gotcha

  • use append only to append new value to given slice, not to create new one:
someSlice = append(someSlice, newElement)
  • if you want to create new slice based on old one with some appended value, always copy it first (example function credits go to SO user):
func copyAndAppend(i []int, vals ...int) []int {
j := make([]int, len(i), len(i)+len(vals))
copy(j, i)
return append(j, vals...)
newSlice := append(T(nil), oldSlice...)



Solution Architect, Developer, Consultant

Love podcasts or audiobooks? Learn on the go with our new app.

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