How to add an element to a slice in Golang
What are slices?
Slices are a built-in data type in Golang similar to arrays, except that a slice has no specified length. All elements within a slice must have the same type.
The code below shows how to declare a slice literal with the string type specification.
newSlice := []string{"a", "b", "c", "d"}
How to add an element to a slice
To add an element to a slice, you can use Golang’s built-in append method. append adds elements from the end of the slice.
The syntax of the append method is shown below:
func append(s []T, vs ...T) []T
The first parameter to the append method is a slice of type T. Any additional parameters are taken as the values to add to the given slice.
Note: The values to add to the
slicemust be of the same type specification as thesliceitself.
The append method returns a slice that contains all the original values in addition to the newly added values. If the backing array of the given slice is too small to handle the addition of the new elements, the append method allocates a bigger array to which the returned slice points.
You can read more about the
appendmethod here.
Code
The code below shows how to add elements to a slice.
package mainimport ("fmt")func main(){// initialize a slice literalnewSlice := []string{"a", "b", "c", "d"}fmt.Println("The original slice is:", newSlice)// add an element to the slicenewSlice = append(newSlice, "e")fmt.Println("The updated slice is:", newSlice)// add multiple values to the slicenewSlice = append(newSlice, "f", "g", "h")fmt.Println("The final slice is:", newSlice)}
Explanation
In the code above:
-
In line 4: We import the
fmtpackage for printing. -
In line 10: We initialize a
sliceliteral of thestringtype callednewSlice. At the time of declaration,newSlicecontains values. -
In line 14: We use the
appendmethod and then add the elementetonewSlice. -
In line 18: We use the
appendmethod to add the elementsf,g, andhtonewSlice. The output is the finalsliceafter all additions.