Sobes.tech
Middle+

What is the difference between a slice and an array in Go?

sobes.tech AI

Answer from AI

In Go, arrays and slices are different data types with different semantics and behaviors.

  • Array — a fixed-size sequence of elements of the same type. The size of the array is set at declaration and cannot be changed. Arrays are passed by value, meaning they are copied when assigned or passed to a function.

  • Slice — a dynamic, resizable view on an array. A slice contains a pointer to the underlying array, along with its length and capacity. When the size of a slice changes (e.g., adding elements), a new array may be allocated and data copied.

Example:

var arr [3]int = [3]int{1, 2, 3} // fixed-size array
var s []int = arr[:2]            // slice referencing part of the array

s = append(s, 4) // adding an element, possibly allocating a new array

Key differences:

  • Arrays have a fixed size, slices are dynamic.
  • Slices are a structure with a pointer to an array, length, and capacity.
  • Passing an array to a function copies the entire array, passing a slice copies the structure with the pointer, which is more efficient.

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