Slice vs Array

1 min read Tweet this post

In Go, slices and arrays are both data structures used to store collections of values. However, they have some important differences:

  1. Size: An array has a fixed size, determined when it is declared, while a slice has a dynamic size that can change during runtime.
  2. Syntax: An array is declared with a size in square brackets, for example array := [3]int{1, 2, 3}. A slice is declared with no size in square brackets, for example slice := []int{1, 2, 3}.
  3. Capacity: A slice has a concept of capacity, which is the maximum number of elements that can be stored in the underlying array before a new array is created. The capacity of a slice can be changed using the make function.
  4. Modification: Arrays cannot be resized, but slices can be resized dynamically. Slices also provide various functions, such as append, copy, and delete, that make it easier to modify their contents.

In general, slices are more flexible and convenient to use than arrays in Go, and are the preferred data structure for storing collections of values. However, there are some use cases where arrays are still more appropriate, such as when you need to store large amounts of data in memory, or when you need to perform low-level operations on the data.

go slice array