Junior — Middle
What will happen if you try to add an element to a slice whose length has reached its maximum capacity?
sobes.tech AI
Answer from AI
If you try to add an element to a slice in Go, which has reached its maximum capacity, an automatic allocation of a new array with increased capacity occurs. The contents of the old array are copied to the new one, and the slice reference is updated to this new array. Thus, the slice expands dynamically, and the element is added successfully.
Example:
s := make([]int, 3, 3) // length and capacity are both 3
s[0], s[1], s[2] = 1, 2, 3
s = append(s, 4) // capacity increases, element is added
fmt.Println(s) // [1 2 3 4]
Important: this process can be time-consuming and memory-intensive, so if the size is known in advance, it is better to allocate sufficient capacity.