Sobes.tech
Senior

What will happen to the data in the second slice if it is created from the first with capacity 5, and then capacity is increased to 10?

sobes.tech AI

Answer from AI

If the second slice is created from the first with a capacity of 5, and then the capacity of the first slice is increased to 10, the data in the second slice will not change automatically.

Explanation:

  • In Go, a slice is a structure with a pointer to an array, a length, and a capacity.
  • The second slice, created from the first, points to the same underlying array but has its own length and capacity.
  • If the capacity of the first slice increases (for example, when expanding with append, which allocates a new array), the underlying array of the first slice changes.
  • The second slice will continue to point to the old array, as it is not updated automatically.

Result: the second slice will point to the old array with capacity 5, and changes to the capacity of the first slice will not affect it. If the first slice expands with a new array allocation, the second slice will still point to the old array, which may lead to data desynchronization.

Example:

s1 := make([]int, 0, 5)
s2 := s1[:3] // slice from s1 with capacity 5

s1 = append(s1, 1, 2, 3, 4, 5, 6) // capacity of s1 increased to 10, new array allocated

// s2 still points to the old array with capacity 5
What will happen to the data in the second slice if… - sobes.tech