Understanding arrays

I’m trying to understand what is happening here. git hub link to code

var twoD [2][3]int
for b := 0; b <2; b++ {
for c := 0; c <3; c++ {
twoD[b][c] = b + c
}
}
fmt.Println(“2d:”, twoD)

This is the basic set up and it works but when I change b <3 or 4 it says :
goroutine 1 [running]:
main.main()
c:/path to file/tut.go:14 +0x39a
exit status 2

So I’m wondering why that happens.
Also if I add a 4 to the first [4] [3] it gives 4 sets of arrays instead of 2. I didn’t expect that but OK. So could someone please explain why it is doing what it’s doing. Thanks

I think you need to check some basics about arrays, and also Go arrays. But to answer your doubts:

  1. If you change your condition from b < 2 to b < X, it will fail for any X that meets X > 2. This is because the size of twoD is 2 (it’s an array of [3]int arrays with 2 [3]int elements), and arrays in Go being 0-indexed, the existing elements are at positions 0 and 1. So trying to access b[2], b[3], etc. will panic as you are trying to read beyond the array’s size.

  2. Well, you are actually defining twoD to be an array of [3]int arrays of size 4, so 4 is the amount of elements (in this case, arrays) it contains. To make it clear, if you declare var a [4]int you are declaring an array of 4 ints, var a [4]string declares an array of 4 strings, etc., so in your case var fourD [4][3]int declares an array of 4 [3]int arrays.

1 Like

Ok I get the second part no problem. The first part is a bit more difficult, but I think I get it. First off is that the correct or best way to write that code? I assumed I was creating 2 sets of arrays one with [2]int and another with [3] int not 2 sets of [3]int. So I get that part, but again when I set twoD [b] that is telling it how many sets of arrays to create? Is that correct? So when originally twoD[2] but I set b<3 that creates the issue correct? Because twoD[2] will not accept anything greater than 2 int 0,1.

Yep, an array is declared as var identifier [size]type, so if you replace size with 2 and type with [3]int, you get the array (sized 2) of int arrays (each sized 3). And when talking arrays, they are always fixed size and the type is actually the combination of the size and the array’s elements type, so for example [2]int and 3[int] are different types. As the tour states:

The type [n]T is an array of n values of type T .

The expression
var a [10]int
declares a variable a as an array of ten integers.

An array’s length is part of its type, so arrays cannot be resized.

And, as mentioned, trying to access an element at an index out of the array’s bounds is illegal and will make the program panic.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.