Beginner Fundamentals

Arrays

An array is a fixed-size collection of elements that all share the same type. The size is part of the type and cannot change.

Declaring an array

var numbers [3]int
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
fmt.Println(numbers) // [10 20 30]

Elements start at their zero value, so an unset int element is 0.

Array literals

You can declare and fill an array in one line.

primes := [4]int{2, 3, 5, 7}
fmt.Println(primes) // [2 3 5 7]

Let the compiler count the elements with ...:

days := [...]string{"Mon", "Tue", "Wed"}
fmt.Println(len(days)) // 3

Length and iteration

len gives the number of elements, and range iterates over them.

for i, v := range primes {
    fmt.Println(i, v)
}

Fixed size

Because the size is fixed, arrays are less common in everyday Go code. For collections that grow, you use slices, covered next.