Sobes.tech
Junior — Middle

How does the length of a slice change after applying the append function in Go?

sobes.tech AI

Answer from AI

In the Go language, the append function adds elements to a slice and returns a new slice. After applying append, the length of the slice increases by the number of added elements. At the same time, if the internal array of the slice cannot accommodate the new elements, a new array is created, and the slice points to it.

Example:

s := []int{1, 2, 3}
fmt.Println(len(s)) // 3
s = append(s, 4, 5)
fmt.Println(len(s)) // 5

Thus, the length of the slice after append is equal to the original length plus the number of added elements.