Sobes.tech
Junior — Middle

How can elements be added to an existing slice without recreating it?

sobes.tech AI

Answer from AI

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 allows, it does not create a new underlying array, but simply extends the existing one.

Example:

slice := []int{1, 2, 3}
slice = append(slice, 4, 5) // add elements 4 and 5
fmt.Println(slice) // [1 2 3 4 5]

If the capacity is insufficient, append creates a new array and returns a new slice, so it’s important to assign the result back to the slice variable.

How can elements be added to an existing slice… - sobes.tech