An array in Go is a fixed-size collection of elements of the same type. Once you declare an array with a specific length, that length cannot be changed. The array’s length is part of its type.
var ages [2]byte // array of 2 bytesvar tags [5]string // array of 5 stringsvar zero [0]byte // zero-length array (no memory)var nums [2 + 1]int // length can be a constant expression
Arrays can contain other arrays, creating multi-dimensional structures:
// 2D array: 2 students, each with 3 gradesstudents := [...][3]float64{ {5, 6, 1}, {9, 8, 4},}var sum float64for _, grades := range students { for _, grade := range grades { sum += grade }}const N = float64(len(students) * len(students[0]))fmt.Printf("Avg Grade: %g\n", sum/N)
You can access elements using multiple indices:
students[0][0] = 5 // First student's first gradestudents[1][2] = 4 // Second student's third grade
books := [3]string{"Book A", "Book B", "Book C"}// With index and valuefor i, book := range books { fmt.Printf("%d: %s\n", i, book)}// Just the valuefor _, book := range books { fmt.Println(book)}// Just the indexfor i := range books { fmt.Println(i)}
In practice, slices are used much more frequently than arrays in Go. Arrays are the foundation upon which slices are built. See the Slices documentation for the more flexible alternative.