๐ŸŽ“ A1Learner
๐Ÿ”

Go Arrays

An array holds a fixed number of values of one type. The length of an array is part of its type.

Read items by index

The array holds three numbers. Each print line reads one item by its index.

package main

import "fmt"

func main() {
	nums := [3]int{10, 20, 30}
	fmt.Println(nums[0])
	fmt.Println(nums[1])
	fmt.Println(nums[2])
}

Let Go count the length

Three dots inside the brackets let Go count the items. The whole array prints first and the length prints next.

package main

import "fmt"

func main() {
	nums := [...]int{5, 10, 15, 20}
	fmt.Println(nums)
	fmt.Println(len(nums))
}

Change one item

The second item starts as 2. A new value at index 1 replaces it.

package main

import "fmt"

func main() {
	nums := [3]int{1, 2, 3}
	nums[1] = 9
	fmt.Println(nums)
}

Print the whole array

One print line shows every item. The values appear inside square brackets.

package main

import "fmt"

func main() {
	nums := [3]int{3, 1, 2}
	fmt.Println(nums)
}

Example

package main

import "fmt"

func main() {
	temps := [4]int{20, 25, 22, 21}
	warmest := temps[0]
	total := 0
	for i := 0; i < len(temps); i++ {
		if temps[i] > warmest {
			warmest = temps[i]
		}
		total += temps[i]
	}
	fmt.Println("Warmest:", warmest)
	fmt.Println("Average:", total/len(temps))
}

Key points

  • An array type names the length and the item type.
  • Indexes start at 0 for the first item.
  • Use len to read the length of an array.
  • Printing an array shows all its values in order.
  • A value in an array can change at any index.

In this example, temps holds four temperatures. The loop visits each item by index. It keeps the largest value in warmest and adds each value to total. The average uses whole number division, so 88 divided by 4 prints as 22.

Note

Two arrays with different lengths have different types.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

How many items does a [3]int array hold?