Sobes.tech
Middle

Can we add elements to a new slice (subslice)?

sobes.tech AI

Answer from AI

In Go, slices are dynamic structures that reference an underlying array. When you create a subslice, for example sub := original[1:3], it refers to the same underlying array as the original slice.

You can add elements directly to a subslice using the append function. However, if adding elements causes the slice's size to exceed the capacity of the underlying array, a new array will be created, and the subslice will no longer reference the original array.

Example:

original := []int{1, 2, 3, 4, 5}
sub := original[1:3] // sub = [2, 3]
sub = append(sub, 6) // add an element
fmt.Println(sub)      // [2 3 6]
fmt.Println(original) // [1 2 3 4 5] or [1 2 3 6 5], depending on capacity

Thus, you can add elements to a subslice, but keep in mind that if the capacity is exceeded, a new array is created, and changes will not affect the original slice.

Can we add elements to a new slice (subslice)? — Golang - sobes.tech