How to Append To A Slice in Golang

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


Hello, fellow Go programmers! Today, we’re going to explore the fascinating world of slices in Go, and how to append to them. Slices in Go are easy to use and fascinating. So, let’s dive in and see what we can discover!

First, let’s start with the basics. In Go, a slice is a dynamically-sized array that can grow or shrink as needed. It’s a powerful feature that allows us to work with collections of data in a flexible way. To create a slice, we use the make() function, like so:

mySlice := make([]int, 0)

This creates an empty slice of integers. But how do we add elements to this slice? That’s where the append() function comes in. We use append() to add elements to a slice, like so:

mySlice = append(mySlice, 42)

This adds the integer 42 to the end of the slice. What if we want to add multiple elements at once? No problem! We can pass a comma-separated list of values to the append() function, like so:

mySlice = append(mySlice, 1, 2, 3)

This adds the integers 1, 2, and 3 to the end of the slice.

But that’s not all! append() is also smart enough to handle growing the slice as needed. If the underlying array that the slice is based on is not large enough to hold the new elements, append() will allocate a new, larger array and copy the existing elements over. This means that we can add as many elements as we want to a slice without having to worry about its capacity.

And what about inserting elements into a slice at a specific index? Can we do that? Absolutely! We can use the copy() function to shift elements over and make room for new ones. Here’s an example:

mySlice = append(mySlice[:2], append([]int{4, 5}, mySlice[2:]...)...)

This inserts the integers 4 and 5 at index 2 in the slice. We’re using slicing syntax to create three sub-slices:

  • the first two elements of the original slice (mySlice[:2]),
  • the new elements we want to insert ([]int{4, 5}),
  • and the rest of the original slice (mySlice[2:]).

We then use append() to concatenate these three slices together and create the new slice.

In conclusion, working with slices in Go is a fascinating and powerful feature that allows us to work with collections of data in a flexible way. With the append() function, we can add elements to a slice with ease, and the copy() function allows us to insert elements at a specific index. So, let’s get slicing and dicing with Go!


Questions or comments? Reach out to me


Learn how to leverage the Go Standard Library like a PRO.

I just created a new course, The Go Standard Library, check it out!