Sobes.tech
Middle+

Tell me about working with slices in Go: how do capacity and length work, and what happens when you go out of bounds?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity.

  • Length (len) — the number of elements available in the slice.
  • Capacity (cap) — the maximum number of elements the slice can hold, starting from the current pointer.

For example, if you have an array of 5 elements, and a slice referencing the first 3, then len=3, cap=5.

Exceeding the slice boundaries (for example, accessing an element with index >= len) causes a panic (runtime panic: index out of range). However, exceeding the capacity is not possible directly, as the slice does not allow access to elements beyond length.

If you extend a slice using append and the length exceeds capacity, Go automatically allocates a new array with increased capacity, copies the data, and returns a new slice.

Example:

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

// s[3] will cause a panic, as index 3 >= len(s)
// but you can do s = s[:5] to extend the length to capacity
s = s[:5]
fmt.Println(s) // [1 2 3 4 5]

// appending beyond capacity will create a new array
s = append(s, 6) // new array, len=6, cap>=6