Both slices and arrays are data structures for storing collections of elements, but they have some key differences:
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.[5]int
for an array of 5 integers.make()
. Slices are represented as []T
, where T
is the type of the elements they contain.make()
.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]