Sobes.tech
Middle+

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

sobes.tech AI

Answer from AI

In Go, an array is a fixed-size structure defined at declaration, and the size of the array cannot change during runtime. A slice, however, is a dynamic, resizable type that represents a reference to a part of an array.

Main differences:

  • Arrays have a fixed size, slices are dynamic.
  • A slice contains a pointer to an array, along with its length and capacity.
  • Slices are more convenient for working with mutable collections.

Example:

var arr [3]int = [3]int{1, 2, 3} // fixed-size array

slice := arr[0:2] // slice referencing part of the array

slice = append(slice, 4) // slice can expand; a new array is created if necessary

Thus, slices are a more flexible and commonly used type for working with sequences in Go.