Arrays and slices are ways to create “lists” of data in Go. The key difference between both is that arrays are of fixed size, while slices can grow and shrink in size.

Arrays

The type [n]Tis an array of nvalues of type T.

var a [10]int

Is an empty array. Values can be accessed by: a[0] = 10

Arrays can be initialized when being declared

var a [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 
fmt.Println(a)

Arrays are fixed in size.

Slices

Slices aren’t fixed in size.

[]Tis a slice with elements of type T

Slices can be created like this:

var a []int = []int{1, 2, 3, 4, 5}
  • Slices don’t store any data
  • Slices describe a section of an array that is created underlying
  • Important: Other slices that share the same underlying array will see changes committed to a slice.
  • TL;DR: Slices are like references to arrays, and arrays are always used under the hood

Array vs. slice literal

// This is an array literal:
 
[3]bool{true, true, false}
 
// And this creates the same array as above, then builds a slice that references it:
 
[]bool{true, true, false}

Slice length and capacity

  • Length: Number of elements it contains
  • Capacity: Number of elements in the underlying array

Functions len()and cap()can be used for this purpose.

Appending values to a slice

var aSlice []int = []int{1, 2, 3, 4, 5}
 
// append a value to the slice
aSlice = append(aSlice, 6)

Multiple values can be appended once: append(aSlice, 1, 2, 3)

Range on slices

for i, val := range a {
	fmt.Println(i, val)
}

The first variable returned is always the index of the value. To “skip” this variable, use the following trick: for _, val := range a

Slices with make

  • Used to create dynamically sized arrays
  • makeallocates a zeroed array and returns a slice that refers to this array
  • To append values to slices successfully, one doesn’t need to use make

Why not always use slices in Go?

As slices offer more flexibility over arrays, one might come to the conclusion to use them always. While this is technically possible and might not come with downsides at first glance, there is something more to consider: Performance.

Slices are not as good when it comes to performance compared to arrays. One of the reasons is that arrays are predicable, as they are fixed in size. Therefore, the compiler can optimize memory usage etc.

Due to this reason, try to use arrays, when you don’t have a use case for a slice, e. g. when having a static list of data.

Next Chapter: Pointers