Since slices are dynamically-sized, you can append elements to a slice using Golang’s built-in append
method.
The
syntax of the append
method is as follows:
slice = append(slice, elem1, elem2, ...)
The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended.
The resulting value of append
is a slice containing all the elements of the original slice plus the provided values. The original slice is not directly affected by append
.
If the backing array of
s
is too small to fit all the given values, a bigger array will be allocated. The returned slice will point to the newly allocated array.
The code snippet below demonstrates how to append a slice in Golang:
package mainimport "fmt"// Helper function to. print slicesfunc printSlice(s []int) {fmt.Printf("length=%d capacity=%d %v\n", len(s), cap(s), s)}func main() {var slice []int // Create an empty slice of type int.printSlice(slice)// Append works on nil slices.slice = append(slice, 0)printSlice(slice)// Slices can be appended to as many times.slice = append(slice, 1)printSlice(slice)// We can add more than one element at a time.slice = append(slice, 2, 3, 4)printSlice(slice)}
Free Resources