Arrays vs Slices

Both slices and arrays are data structures for storing collections of elements, but they have some key differences:

Size
  • Arrays have a fixed size that is determined when they are declared. Once you create an array with a specific size, you cannot change that size.
  • Slices, on the other hand, are dynamic and can grow or shrink as needed. Slices are essentially references to underlying arrays.
Declaration
  • Arrays are declared with a specific size and type, like [5]int for an array of 5 integers.
  • Slices are created from arrays, other slices, or using built-in functions like make(). Slices are represented as []T, where T is the type of the elements they contain.
Initialization
  • Arrays are initialized when declared, or you can use the zero value for the type if you don't specify initial values.
  • Slices are often created by slicing an existing array or slice. You can also create an empty slice with make().
Passing to Functions
  • When you pass an array to a function, you're effectively passing a copy of the entire array. This can be inefficient for large arrays.
  • When you pass a slice to a function, you're passing a reference to the underlying array, which is more efficient and allows the function to modify the original data.

Here's a basic example to illustrate the difference:

// Array
var arr [5]int             // Declares an array with a fixed size of 5
arr[0] = 1
arr[1] = 2

// Slice
slice := []int{1, 2, 3}    // Creates a slice with dynamic size
slice = append(slice, 4)   // Slices can grow

fmt.Println(arr)            // [1 2 0 0 0] (zero values for unset elements)
fmt.Println(slice)          // [1 2 3 4]