How to append a slice in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. A slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array.
As we already know that slice is dynamic, so the new element can be appended to a slice with the help of append() function. This function appends the new element at the end of the slice.
func append(s T, x ...T) T
Here, this function takes s slice and x…T means this function takes a variable number of arguments for the x parameter. Such type of function is also known as a variadic function.
If the slice is backed by the array and arrays are fixed length, then how is that possible a slice is a dynamic length?.
Well, the answer is when the new elements append to the slice a new array is created. Now, the elements present in the existing array are copied into a new array and return a new slice reference to this array(new array). So, due to this, the capacity of the slice is going to be double from the old capacity(As shown in example 1). But if the existing slice has enough capacity to hold new elements, then no new array is created and the elements store in the existing underlying array(As shown in example 2).
Slice_1: [234 567 7890 1234 234] Length of Slice_1: 5 Capacity of Slice_1: 5 Slice_2: [Geeks For Geeks] Length of Slice_2: 3 Capacity of Slice_2: 3 New slice_1: [234 567 7890 1234 234 1000] New length of slice_1: 6 New capacity of slice_1: 12 New slice_2: [Geeks For Geeks GFG] New length of slice_2: 4 New capacity of slice_2: 6
Slice : [123 456 789 977] Length: 4 Capacity: 6 Slice : [123 456 789 977 3454 678] Length: 6 Capacity: 6
Appending to nil slice: As we know that zero value slice type is nil and the capacity and the length of such type of slice is 0. But with the help of append function, it is possible to append values to nil slice.
Slice :  Length: 0 Capacity: 0 Slice : [89 45 67 23] Length: 4 Capacity: 4
Appending to another slice using … operator: You are allowed to append one slice to another with the help of … operator.
Slice_1: [234 567 7890 1234 234] Length of Slice_1: 5 Capacity of Slice_1: 5 Slice_2: [10 100 1000 10000] Length of Slice_2: 4 Capacity of Slice_2: 4 New slice_1: [234 567 7890 1234 234 10 100 1000 10000] New length of slice_1: 9 New capacity of slice_1: 12