Junior — Middle
How are new elements added to a slice in the Go language?
sobes.tech AI
Answer from AI
In Go language, the built-in function append is used to add new elements to a slice. It takes a slice and one or more elements to add, and returns a new slice with the added elements.
It is important to remember that slices in Go have an internal structure with a pointer to an array, length, and capacity. If the capacity of the slice is insufficient when adding elements, append will create a new array and return a slice pointing to it.
Example:
slice := []int{1, 2, 3}
slice = append(slice, 4, 5)
// slice now contains [1 2 3 4 5]
Always assign the result of append back to the slice variable, as it may change.