An array is a fixed-length series of elements of a chosen type. It is an example of a composite data type - not primitives.
Use subscript notation []
to index elements.
Indices start at 0.
Elements are all initialized to zero value. Zero value means the zero-value of the type that the array is composed of. For example, the zero value of String is just the empty string.
Example of initialising an array:
var x [5]int // x is an array of 5 integers
x[0] = 2
fmt.Printf(x[1]) // prints 0
An array literal is a predefined array with values.
var x [5]int = [5]{1, 2, 3, 4, 5}
The length of the literal must be the length of the array.
You can use the ...
operator to infer the size of the array literal based on the number of elements passed. It is necessary put either a number or ...
into the []
when declaring an array literal, otherwise Go infers it to be a slice.
x := [...]int{1, 2, 3, 4} // the size of x is 4
We use the :=
operator to declare a variable x
and assign it a value in the same line (we don’t even have to sepcify the type of x
)
Just use a for loop using range
keyword. range
returns two values - the index and the value. In each iteration, the index increments and returns the value of the array at that index
x := [3]int{1, 2, 3}
for i, v range x {
fmt.Printf("ind %d, val %d", i, v)
}
// output:
0 1
1 2
2 3
Slices can be usually instead of an array. A slice is basically a “window” on an underlying array.
Slices have variable size - you can increase the size of the slice (but you cannot do this for arrays - array if fixed-size).