Task 1: What will the code with slices output? (append, capacity, shared underlying array)
sobes.tech AI
Answer from AI
In Go, slices are structures that contain a pointer to an array, a length, and a capacity. When using the append function, elements are added to the slice. If the length of the slice exceeds its capacity during addition, a new underlying array is created, and data is copied there. If the capacity allows, the addition occurs in the same array.
Example:
s := make([]int, 2, 4) // len=2, cap=4
s[0], s[1] = 1, 2
s2 := append(s, 3) // len=3, cap=4, shared underlying array
s3 := append(s2, 4) // len=4, cap=4, shared underlying array
s4 := append(s3, 5) // len=5, cap=8, new array
fmt.Println(s, s2, s3, s4)
Here, the first three slices (s, s2, s3) share the same underlying array, and when adding the fifth element, a new array with increased capacity is created. This is important because modifying elements in slices that share the array affects all slices until reallocation occurs.
Thus, append can either expand the slice within the existing array or create a new array if the capacity is exceeded. This impacts performance and program behavior.