Sobes.tech
Principal

What is the difference between arrays and slices in Go? How does the capacity of a slice change?

sobes.tech AI

Answer from AI

In Go, arrays and slices are different data types:

  • Array — fixed size, size is part of the type, for example [5]int — an array of 5 elements. The size of the array cannot be changed after creation.

  • Slice — dynamic, represents a structure with a pointer to an array, length, and capacity. Slices can be extended by adding elements.

Slice capacity — the maximum number of elements a slice can hold without allocating new memory.

When adding elements using append:

  • If the slice's length is less than its capacity, the new element is simply added.
  • If the length reaches the capacity, a new array with increased capacity (usually twice as large) is created, and data is copied there.

Example:

arr := [5]int{1,2,3,4,5}       // fixed size array
slice := arr[1:3]              // slice with length 2 and capacity 4

fmt.Println(len(slice))        // 2
fmt.Println(cap(slice))        // 4

slice = append(slice, 10)      // add element, length becomes 3
fmt.Println(len(slice))        // 3
fmt.Println(cap(slice))        // 4

slice = append(slice, 20, 30)  // add 2 more elements, length 5
fmt.Println(len(slice))        // 5
fmt.Println(cap(slice))        // >=5, capacity increased

Thus, slices are convenient for working with dynamic collections, while arrays are suitable for fixed data.