Arrays

In Go+, an array is a numbered sequence of elements of a specific length.

Declaration of a one-dimensional array

Here we create an array a that will hold exactly 5 ints. The type of elements and length are both part of the array’s type. By default an array is zero-valued, which for ints means 0s.

var a [5]int println "empty:", a

We can set a value at an index using the array[index] = value syntax, and get a value with array[index].

a[4] = 100 println "set:", a println "get:", a[4]

The builtin len returns the length of an array.

println "len:", len(a)

Use this syntax to declare and initialize an array in one line.

b := [5]int{1, 2, 3, 4, 5} println "dcl:", b

If you don’t want to write the length of the array, you can use this method and let the compiler calculate the length of the array itself.

c := [...]int{1, 2, 3} println c

Declaration of multidimensional arrays

Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.

var twoD [2][3]int for i := 0; i < 2; i++ { for j := 0; j < 3; j++ { twoD[i][j] = i + j } } println "2d: ", twoD

If you need to declare more dimensions, you can extend them yourself, such as declaring a 2*2*3 three-dimensional array

var threeDimensionalArray [2][2][3]int println threeDimensionalArray

tips

If you do not declare the contents of the array in Go+, the compiler automatically initializes the array to 0; For an array of type bool, the initial value is false.

For more array value types, Go+ supports strings, integers, floats, Booleans, etc. See this chapter for details:

Next example: Slices