7. Arrays and Slices — A Book of Go

Louis Petrik
2 min readMay 15, 2024
Source: the author

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. We can add and remove values.

[]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…

--

--