How do you use the append function in the Go language?
In Go language, the append() function is used to add elements to a slice and return a new slice.
The syntax for using the append() function is as follows:
newSlice := append(slice, element1, element2, ..., elementN)
The slice is the part where elements are to be appended, and element1, element2, …, elementN are the elements to be appended.
The example code is shown below:
package main
import "fmt"
func main() {
slice := []int{1, 2, 3}
newSlice := append(slice, 4, 5)
fmt.Println("Original slice:", slice)
fmt.Println("New slice:", newSlice)
}
The output is as follows:
Original slice: [1 2 3]
New slice: [1 2 3 4 5]
The append() function can also append another slice, as shown in the example code below:
package main
import "fmt"
func main() {
slice1 := []int{1, 2, 3}
slice2 := []int{4, 5}
newSlice := append(slice1, slice2...)
fmt.Println("Original slice 1:", slice1)
fmt.Println("Original slice 2:", slice2)
fmt.Println("New slice:", newSlice)
}
The output is:
Original slice 1: [1 2 3]
Original slice 2: [4 5]
New slice: [1 2 3 4 5]
When using the append() function, it is important to keep the following points in mind:
- The append() function returns a new slice, and the original slice is not modified.
- If the number of elements added exceeds the capacity of the slice, the append() function will reallocate a larger underlying array, causing the original slice and the new slice to have different underlying arrays.
- If the number of elements added does not exceed the capacity of the slice, the append() function will append the elements on the underlying array of the original slice.
- If the slice being appended is an empty slice, the append() function will return the original slice.
- If the additional element is a slice, the slice needs to be unpacked using the … operator.