Go: range and len of multidimensional array?
The solution with range is already provided so i'll talk about how to use length (len) to go through a multi-dimesional array in golang.
So if u have an array arr[][]
:
[1,2,3]
[4,5,6]
Now the len(arr)
will output = 2.
while len(arr[1]) will output = 3
.
Sample code is provided here : https://play.golang.org/p/XerzPhkQrhU
In Go as in most languages, what you call a multidimensional array is an array of arrays. The len
operator only gives you the length of the "external" array.
Maybe the var declaration could be clearer for you if you see it as
var a [3]([5]int8)
which also compiles. It's an array of size 3 whose elements are arrays of size 5 of int8.
package main
import "fmt"
func main() {
var a [3][5]int8
for _, h := range a {
fmt.Println(len(h)) // each one prints 5
}
fmt.Println(len(a)) // prints 3, the length of the external array
}
outputs
5
5
5
3
To loop safely through the whole matrix, you can do this :
for _, h := range a {
for _, cell := range h {
fmt.Print(cell, " ")
}
fmt.Println()
}
If you need to change the content, you may do
for i, cell := range h { // i is the index, cell the value
h[i] = 2 * cell
}