Sobes.tech
Senior

What is the difference between slices and arrays in Go?

sobes.tech AI

Answer from AI

In Go, arrays and slices are different data types, although slices are closely related to arrays.

Arrays are fixed-size sequences of elements of the same type. The size of the array is set at declaration and cannot be changed. Arrays are stored entirely in memory, and when passed to functions, they are copied completely.

var arr [3]int = [3]int{1, 2, 3}

Slices are dynamic structures that refer to a part of an array. They contain a pointer to the array, a length, and a capacity. Slices allow working with dynamic sequences; their length can change (for example, when adding elements with append).

var s []int = []int{1, 2, 3}
s = append(s, 4)

Main differences:

  • Arrays have a fixed size, slices are dynamic.
  • Slices are structures that refer to an array, not copy data.
  • When passing an array to a function, a copy is made; with a slice, a reference is passed.

Thus, slices are more flexible and are used much more often in Go.