You may recall from last week’s discussion of N-dimensional arrays that Go doesn’t support multi-dimensional arrays. But the implications of this matter a lot more for slices than they do for arrays.
Slice types
…
Like arrays, slices are always one-dimensional but may be composed to construct higher-dimensional objects. With arrays of arrays, the inner arrays are, by construction, always the same length; however with slices of slices (or arrays of slices), the inner lengths may vary dynamically. Moreover, the inner slices must be initialized individually.
Let’s first look at an example of an array of arrays, which might be represented by a two-dimensional array in some other languages:
twoDims := [5][5]int{}
for _, row := range twoDims {
fmt.Println(row)
}
Which prints:
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
Of note here is that every element in our 5x5 matrix is populated with the zero value of an int
(0).
However, since slices are of dynamic length, and their zero value is nil
, we have a different behavior if we switch to slices for our example:
twoDims := [][]int{}
for _, row := range twoDims {
fmt.Println(row)
}
Which outputs nothing.
But lets ensure our top-level slice still has 5 elements:
twoDims := make([][]int, 5)
for _, row := range twoDims {
fmt.Println(row)
}
Now it outputs:
[]
[]
[]
[]
[]
So we have a slice that contains 5 nil slices.
Let’s drive the point home with just one more example, and populate a couple of these slices:
twoDims := make([][]int, 5)
twoDims[0] = []int{0, 0, 0, 0, 0, 0, 0, 0}
twoDims[3] = []int{3, 6, 9}
for _, row := range twoDims {
fmt.Println(row)
}
This one prints:
[0 0 0 0 0 0 0 0]
[]
[]
[3 6 9]
[]
Hopefully it’s clear now that N-dimensional slices in Go truly are not a thing. We have instead slices of slices. And those sub-slices are not related to each other in terms of length or capacity.
Quotes from The Go Programming Language Specification Version of December 15, 2022