Junior — Middle
Kuidas lisada elemente olemasolevale slice'ile ilma seda uuesti loomata?
sobes.tech AI
Vastus AI-lt
In Go, to add elements to an existing slice without recreating it, the built-in append function is used. It adds new elements to the slice, increasing its capacity if necessary. If the current capacity of the slice allows, no new slice is created, and the elements are simply added to the existing array.
Example:
slice := []int{1, 2, 3}
slice = append(slice, 4, 5) // adding elements 4 and 5
fmt.Println(slice) // [1 2 3 4 5]
If the capacity is insufficient, append will create a new array and return a new slice, so it is important to assign the result back to the slice variable.