N-dimensional arrays

March 1, 2023

There’s one sentence at the end of the paragraph yesterday about arrays, which I saved for today, as I think it deserves special attention:

Array types

Array types are always one-dimensional but may be composed to form multi-dimensional types.

[3][5]int
[2][2][2]float64  // same as [2]([2]([2]float64))

The two examples provided do not represent a 2- and 3-dimensional array, therefore. Rather, they represent an array of arrays, and an array of arrays of arrays, respectively.

This might seem like a distinction without a difference, and if we were limited strictly to fixed-length arrays, it might be. But as we’ll see when we discuss the slice type next, we’ll see that this distinction actually makes a difference.

For now, though, just remember that there are no 2-, 3-, or higher-dimensional arrays in Go. Only one-dimensional arrays, which may in turn be of other 1-dimensional arrays, in effect, then, building up N-dimensionality.

Quotes from The Go Programming Language Specification, Version of January 19, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Clear

Clear The built-in function clear takes an argument of map, slice, or type parameter type, and deletes or zeroes out all elements [[Go 1.21(https://go.dev/ref/spec#Go_1.21)]]. Call Argument type Result clear(m) map[K]T deletes all entries, resulting in an empty map (len(m) == 0) clear(s) []T sets all elements up to the length of s to the zero value of T clear(t) type parameter see below clear is a relatively recent addition to Go, added just over a year ago.


Evaluation of range expressions

For statements with range clause … The range expression x is evaluated once before beginning the loop, with one exception: if at most one iteration variable is present and len(x) is constant, the range expression is not evaluated. The first part of this seems pretty self-evident, as it follows the same pattern as a for statement with a for clause: The expression needs to be evaluated once before the loop executes.


Conversions from slice to array or array pointer

Conversions from slice to array or array pointer … Converting a slice to an array yields an array containing the elements of the underlying array of the slice. Similarly, converting a slice to an array pointer yields a pointer to the underlying array of the slice. In both cases, if the length of the slice is less than the length of the array, a run-time panic occurs. s := make([]byte, 2, 4) a0 := [0]byte(s) a1 := [1]byte(s[1:]) // a1[0] == s[1] a2 := [2]byte(s) // a2[0] == s[0] a4 := [4]byte(s) // panics: len([4]byte) > len(s) s0 := (*[0]byte)(s) // s0 !

Get daily content like this in your inbox!

Subscribe