Go Arrays – Declare, Initialize, and Access Elements
In Go, an array is a fixed-length, ordered collection of elements of the same type. The array length is part of its type, so [5]int and [10]int are different types.
Array elements are stored in index order. The first element is at index 0, the second at index 1, and the last element is at index len(array)-1.
For example, the first five prime numbers can be stored in an integer array as [2, 3, 5, 7, 11]. Every element has type int, and its position identifies its order in the sequence.
This tutorial explains how to declare a Go array, initialize it with values, access and update elements, iterate over it, find its length, work with arrays of strings and structs, and understand when a slice is more appropriate.
Go Array Declaration Syntax
To declare an array in Go, specify its name, fixed length, and element type.
var array_name [size] datatype
In this syntax:
vardeclares a variable.array_nameis the identifier used to refer to the array.sizeis the fixed number of elements in the array.datatypeis the type shared by all array elements.
The following example declares an array named primes that can store five integer values.
example.go
package main
func main() {
var primes [5] int
}
This program does not compile because the local variable primes is declared but not used. Go reports unused local variables as compile-time errors. In a complete program, use the array, for example by printing it or assigning and reading its elements.
Zero Values in a Newly Declared Go Array
When an array is declared without explicit element values, Go initializes every element with the zero value of its type. Integer elements become 0, strings become empty strings, Boolean values become false, and pointer elements become nil.
package main
import "fmt"
func main() {
var numbers [4]int
var names [3]string
var flags [2]bool
fmt.Println(numbers)
fmt.Printf("%q\n", names)
fmt.Println(flags)
}
Output
[0 0 0 0]
["" "" ""]
[false false]
Set Go Array Values by Index
To set an array element, place its zero-based index inside square brackets and assign a value of the array’s element type.
arrayName[index] = value
The valid indices for an array of length five are 0 through 4.
example.go
package main
import "fmt"
func main() {
var primes [5]int
primes[0] = 2
primes[1] = 3
primes[2] = 5
primes[3] = 7
primes[4] = 11
fmt.Println(primes)
}
Output
[2 3 5 7 11]
Declare and Initialize a Go Array with Values
An array can be declared and initialized in one statement with an array literal. The number of values must not exceed the declared length.
example.go
package main
import "fmt"
func main() {
primes := [5]int{2, 3, 5, 7, 11}
fmt.Println(primes)
}
Output
[2 3 5 7 11]
Let Go Infer the Array Length with […]
Use [...] in an array literal when Go should count the supplied values and infer the array length.
arrayName := [...]ElementType{value1, value2, value3}
package main
import "fmt"
func main() {
primes := [...]int{2, 3, 5, 7, 11}
fmt.Println(primes)
fmt.Println(len(primes))
}
Output
[2 3 5 7 11]
5
The [...] form still creates an array, not a slice. Its inferred length remains part of its type.
Initialize Selected Go Array Indices
An array literal can assign values to specific indices. Elements that are not listed receive their zero value.
package main
import "fmt"
func main() {
values := [6]int{0: 10, 3: 40, 5: 60}
fmt.Println(values)
}
Output
[10 0 0 40 0 60]
Access Go Array Elements Using an Index
Use array-index notation to read the value stored at a particular position.
value := arrayName[index]
example.go
package main
import "fmt"
func main() {
primes := [5]int{2, 3, 5, 7, 11}
fmt.Println("Value at index 0 is : ", primes[0])
fmt.Println("Value at index 1 is : ", primes[1])
fmt.Println("Value at index 2 is : ", primes[2])
}
Output
Value at index 0 is : 2
Value at index 1 is : 3
Value at index 2 is : 5
Using an index outside the valid range causes an error. A constant index known to be invalid is rejected at compile time. A variable index that is invalid at runtime causes an index-out-of-range panic.
Find the Length of a Go Array with len()
The built-in len() function returns the number of elements in an array.
package main
import "fmt"
func main() {
languages := [4]string{"Go", "Python", "Java", "C++"}
fmt.Println("Array length:", len(languages))
fmt.Println("Last element:", languages[len(languages)-1])
}
Output
Array length: 4
Last element: C++
Iterate Over a Go Array with for and range
A traditional for loop is useful when the index is needed to read or update elements.
package main
import "fmt"
func main() {
numbers := [5]int{10, 20, 30, 40, 50}
for i := 0; i < len(numbers); i++ {
fmt.Printf("numbers[%d] = %d\n", i, numbers[i])
}
}
Output
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
A range loop returns both the index and a copy of the value at that index.
package main
import "fmt"
func main() {
primes := [5]int{2, 3, 5, 7, 11}
for index, value := range primes {
fmt.Printf("Index %d contains %d\n", index, value)
}
}
Output
Index 0 contains 2
Index 1 contains 3
Index 2 contains 5
Index 3 contains 7
Index 4 contains 11
Use the blank identifier _ when either the index or value is not required.
for _, value := range arrayName {
// use value
}
Update Go Array Elements Inside a Loop
The value variable produced by range is a copy. Assigning to it does not update the original array. To change array elements, assign through the index.
package main
import "fmt"
func main() {
numbers := [4]int{1, 2, 3, 4}
for i := range numbers {
numbers[i] *= 10
}
fmt.Println(numbers)
}
Output
[10 20 30 40]
Declare and Initialize a Go Array of Strings
A Go array can store strings when its element type is string.
package main
import "fmt"
func main() {
colors := [4]string{"red", "green", "blue", "yellow"}
fmt.Println(colors)
fmt.Println(colors[2])
}
Output
[red green blue yellow]
blue
Initialize a Go Array of Structs
Arrays can contain user-defined struct values as long as every element has the same struct type.
package main
import "fmt"
type Product struct {
Name string
Stock int
}
func main() {
products := [3]Product{
{Name: "Keyboard", Stock: 12},
{Name: "Mouse", Stock: 20},
{Name: "Monitor", Stock: 5},
}
for _, product := range products {
fmt.Printf("%s: %d\n", product.Name, product.Stock)
}
}
Output
Keyboard: 12
Mouse: 20
Monitor: 5
Multidimensional Arrays in Go
A multidimensional array is an array whose elements are themselves arrays. A two-dimensional array can represent rows and columns.
var matrix [rows][columns]ElementType
package main
import "fmt"
func main() {
matrix := [2][3]int{
{1, 2, 3},
{4, 5, 6},
}
fmt.Println(matrix)
fmt.Println("Value at row 1, column 2:", matrix[1][2])
}
Output
[[1 2 3] [4 5 6]]
Value at row 1, column 2: 6
Copying and Comparing Go Arrays
Assigning one array to another copies all of its elements. The two arrays are separate values after the assignment.
package main
import "fmt"
func main() {
first := [3]int{10, 20, 30}
second := first
second[0] = 99
fmt.Println("first:", first)
fmt.Println("second:", second)
}
Output
first: [10 20 30]
second: [99 20 30]
Arrays can be compared with == and != when their element type is comparable. The arrays must also have the same type, including the same length.
package main
import "fmt"
func main() {
a := [3]int{1, 2, 3}
b := [3]int{1, 2, 3}
c := [3]int{1, 2, 4}
fmt.Println(a == b)
fmt.Println(a == c)
}
Output
true
false
Pass a Go Array to a Function
Arrays are value types. Passing an array to a function copies it, so changes made to the parameter do not affect the original array.
package main
import "fmt"
func changeFirst(values [3]int) {
values[0] = 100
}
func main() {
numbers := [3]int{1, 2, 3}
changeFirst(numbers)
fmt.Println(numbers)
}
Output
[1 2 3]
Pass a pointer to the array when the function must modify the original array.
package main
import "fmt"
func changeFirst(values *[3]int) {
values[0] = 100
}
func main() {
numbers := [3]int{1, 2, 3}
changeFirst(&numbers)
fmt.Println(numbers)
}
Output
[100 2 3]
Go Arrays Compared with Slices
A Go array has a fixed length, while a slice is a dynamically sized view over an underlying array. Most Go programs use slices when the number of elements may change or when functions should accept sequences of different lengths.
| Feature | Go array | Go slice |
|---|---|---|
| Length | Fixed and part of the type | Can vary |
| Declaration example | [5]int | []int |
Can use append() | No | Yes |
| Assignment behavior | Copies all elements | Copies the slice descriptor; underlying data may be shared |
| Common use | Fixed-size records, buffers, and known dimensions | General collections and variable-length data |
To create a slice that refers to an array, use a slicing expression.
package main
import "fmt"
func main() {
array := [5]int{10, 20, 30, 40, 50}
slice := array[1:4]
slice[0] = 99
fmt.Println("Array:", array)
fmt.Println("Slice:", slice)
}
Output
Array: [10 99 30 40 50]
Slice: [99 30 40]
The slice shares the array’s underlying storage, so changing the slice can change the corresponding array element.
Can You Declare a Go Array Without a Length?
An array type must have a length. Writing []int declares a slice type, not an array type. When initializing an array, [...]int{1, 2, 3} lets the compiler infer the length from the provided values.
array := [...]int{1, 2, 3} // array of type [3]int
slice := []int{1, 2, 3} // slice of type []int
Common Go Array Errors and Misunderstandings
- Using an index outside the valid range: an array of length
nhas valid indices from0ton-1. - Expecting an array to grow: arrays have a fixed length and do not support
append(). Use a slice for a growable collection. - Confusing
[...]Twith[]T: the first creates an array with inferred length; the second creates a slice. - Assuming different array lengths have the same type:
[3]intand[4]intare distinct types. - Changing the range value variable: the value returned by
rangeis a copy. Updatearray[index]instead. - Expecting function changes to affect the original array: arrays are copied when passed by value.
Go Array FAQs
How do you initialize an array in Go?
Use an array literal such as numbers := [3]int{10, 20, 30}. You can also let Go infer the length with numbers := [...]int{10, 20, 30}.
What does a Go array contain before values are assigned?
Every element contains the zero value of the array’s element type. For example, an uninitialized [3]int contains [0 0 0].
Can a Go array contain values of different types?
No. All elements must have the array’s declared element type. To group related values of different types, define a struct and create an array of that struct type.
What is the difference between [5]int and []int in Go?
[5]int is an array containing exactly five integers. []int is a slice whose length can vary and which can be extended with append().
Are Go arrays copied when assigned or passed to a function?
Yes. Arrays are value types, so assignment and pass-by-value function calls copy their elements. Use an array pointer or a slice when shared modification is required.
Go Arrays Editorial QA Checklist
- Verify that each array index is between
0andlen(array)-1. - Confirm that every array literal contains values compatible with the declared element type.
- Check that
[...]Texamples are described as arrays and[]Texamples are described as slices. - Ensure examples that modify arrays through functions distinguish value parameters from pointer parameters.
- Confirm that range-loop examples do not imply that assigning to the copied value variable updates the array.
- Run each Go example and compare the actual result with its displayed output block.
Summary of Declaring and Using Arrays in Go
A Go array stores a fixed number of same-type elements. Declare an array with [length]Type, initialize it with an array literal, access elements with zero-based indices, and use len() to obtain its length. Arrays are copied during assignment and pass-by-value function calls. Use slices when the collection length must change or when flexible sequence handling is required.
In this Go Tutorial, we learned how to declare and initialize arrays, access and update elements, iterate over arrays, create arrays of strings and structs, work with multidimensional arrays, and distinguish arrays from slices.
TutorialKart.com