Arrays in Go
By Syncfusion®, Inc. · Last updated
Go arrays: fixed-size lists of one type. Declare and create them, read, update and loop through elements, and learn length, zero values, copying, comparing and 2D arrays.
What Are Arrays?
Array = a fixed number of values of the same type, kept in one variable, in order.
- Each value sits in a numbered slot.
- Index = the slot number. It starts at
0. - Element = one value in the array.
- The size is fixed when the array is made. It never grows or shrinks.
Simple lesson: an array is a row of numbered boxes, all of the same type, and the number of boxes never changes.
A Real-World Example
Think of the shoe rack outside the computer lab.
- The rack has exactly 5 slots. No more, no less.
- Each slot has a number painted on it: 0, 1, 2, 3, 4.
- Each slot holds one pair of shoes.
- To find Ravi's shoes, you go straight to slot 3.
Now the mapping:
- The rack = the array.
- 5 slots = the array's length, fixed forever.
- The painted number = the index.
- Going straight to slot 3 =
rack[3].
Arrays are the base of Go's collections.
In real programs, you will usually use slices, which can grow. Slices are built on top of arrays, so learning arrays first makes slices easy. See Slices.
What You Will Learn
In this lesson, you will learn:
- What an array is, and why its size is fixed.
- How to declare and create arrays.
- How to read, change and loop through elements.
- How to find the length, and what an empty array holds.
- How arrays are copied and compared.
- How to make a grid with a two-dimensional array.
Array Fundamentals
Fixed-Size Arrays
The size is part of the type.
[5]int= an array of 5 ints.[3]int= an array of 3 ints.[5]intand[3]intare different types.
Declaring Arrays
var marks [5]int
[5]is the size.intis the type of every element.- Go fills every slot with the zero value:
0forint.
Creating Arrays
Ways to make an array
Make arrays
package main
import "fmt"
func main() {
var marks [5]int
subjects := [3]string{"Maths", "Science", "English"}
days := [...]string{"Mon", "Tue", "Wed", "Thu", "Fri"}
bonus := [5]int{1: 10, 3: 30}
fmt.Println(marks)
fmt.Println(subjects)
fmt.Println(days, len(days))
fmt.Println(bonus)
}
[0 0 0 0 0]
[Maths Science English]
[Mon Tue Wed Thu Fri] 5
[0 10 0 30 0]
- Printing an array shows all its elements in square brackets.
Simple lesson: write the size and the type, like [5]int, and the size becomes part of the type.
Working with Arrays
Accessing Elements
Click a box, or move the slider, then read or change it.
Try these:
- Index 0 is the first box. Index 4 is the last.
- Index -1 or 5 is outside the array. Reading it is a panic.
Read elements by index
package main
import "fmt"
func main() {
marks := [5]int{91, 78, 85, 66, 99}
fmt.Println("First:", marks[0])
fmt.Println("Third:", marks[2])
fmt.Println("Last:", marks[len(marks)-1])
}
First: 91
Third: 85
Last: 99
- The last index is always
len - 1.
Updating Elements
Change one element
package main
import "fmt"
func main() {
marks := [5]int{91, 78, 85, 66, 99}
marks[3] = 72
marks[1] += 5
fmt.Println(marks)
}
[91 83 85 72 99]
marks[3] = 72replaces the value in slot 3.marks[1] += 5adds 5 to slot 1.
Index Out of Range
Reading past the end
package main
import "fmt"
func main() {
marks := [5]int{91, 78, 85, 66, 99}
i := 5
fmt.Println(marks[i])
}
- The program stops with
panic: runtime error: index out of range [5] with length 5. - If you write the number directly, like
marks[5], Go catches it even before running.
Always keep an index between 0 and len(a) - 1.
A loop like for i := 0; i < len(a); i++ stays inside safely. Using <= goes one step too far.
Iterating Arrays
Two ways to loop
package main
import "fmt"
func main() {
marks := [5]int{91, 78, 85, 66, 99}
for i := 0; i < len(marks); i++ {
fmt.Print(marks[i], " ")
}
fmt.Println()
total := 0
for _, m := range marks {
total += m
}
fmt.Println("Total:", total)
}
91 78 85 66 99
Total: 419
- The classic
forloop uses the index. rangegives the index and value. See Loops.
Simple lesson: use a[i] to read or change a box, keep i between 0 and len - 1, and loop with range.
Array Properties
Array Length
len(a)gives the number of elements.- For an array,
lenis fixed. It is known before the program runs.
Zero Values in Arrays
A new array is full of zero values. See Data Types.
Zero values in arrays
package main
import "fmt"
func main() {
var scores [3]int
var passed [3]bool
var names [3]string
fmt.Println(scores, passed)
fmt.Printf("%q\n", names)
}
[0 0 0] [false false false]
["" "" ""]
Arrays Are Copied
Value type = assigning it, or passing it to a function, makes a full copy.
Arrays are value types. Press Play and watch two separate arrays.
Copying an array makes a new one
- Passing an array to a function also copies it.
- So a function cannot change the caller's array, unless you pass a pointer. See Pointers.
Comparing Arrays
Two arrays can be compared with == when they have the same type (same size and element type).
Compare arrays
package main
import "fmt"
func main() {
key := [4]string{"B", "A", "D", "C"}
asha := [4]string{"B", "A", "D", "C"}
ravi := [4]string{"B", "C", "D", "C"}
fmt.Println(asha == key)
fmt.Println(ravi == key)
}
true
false
==is true only when every element is equal, in the same order.- Comparing
[3]intwith[4]intdoes not build: they are different types.
Two-Dimensional Arrays
2D array = an array of arrays. It is a grid of rows and columns.
A seating plan
package main
import "fmt"
func main() {
seats := [2][3]string{
{"Asha", "Ravi", "Meena"},
{"Kabir", "Priya", "Arjun"},
}
fmt.Println(seats[1][2])
for r, row := range seats {
fmt.Println("Row", r, row)
}
}
Arjun
Row 0 [Asha Ravi Meena]
Row 1 [Kabir Priya Arjun]
seats[1][2]= row 1, column 2.- The first index picks the row. The second picks the seat in that row.
Easy way to remember
- Size is part of the type:
[5]intis not[3]int. - Index from
0tolen - 1. b := acopies the whole array.
Simple lesson: an array's length is fixed, it starts full of zero values, and assigning it makes a full copy.
TL;DR
Array = a fixed number of values of one type:
[5]int.- The size is part of the type.
- Create =
var a [5]int,[5]int{...},[...]string{...},[5]int{1: 10}. Access =
a[i], from0tolen(a) - 1.- Outside that range = a panic.
- Update =
a[i] = value. - Loop =
for i := 0; i < len(a); i++orfor i, v := range a. - Zero values = a new array is full of
0,falseor"". - Copy =
b := acopies everything. Compare ===for the same type. - 2D array =
[rows][cols]T, read witha[r][c].
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
marks[5] in a 5-element array | The last index is 5 | The last index is 4 | index out of range |
marks[1] for the first mark | Indexes start at 1 | Indexes start at 0 | You get the second mark. |
| Adding a sixth value | Arrays can grow | The size is fixed | Use a slice. See Slices. |
| Changing a copy to change the original | b := a shares the data | It copies everything | The original stays the same. |
Comparing [3]int with [4]int | Any two arrays compare | Same size and type only | A build error. |
var n = 5; var a [n]int | Any number can be a size | The size must be a constant | array length n ... must be constant |
for i := 0; i <= len(a); i++ | <= reaches the end | Use < | A panic on the last trip. |
Check Yourself
Exercises
What to Remember
- An array holds a fixed number of values of one type:
[5]int. - The size is part of the type and never changes.
- Indexes run from
0tolen - 1. Anything else panics. - A new array is full of zero values.
- Assigning or passing an array copies all of it.
- Arrays of the same type can be compared with
==.
Next: Slices. You will learn Go's flexible lists, which can grow and share data, and how they are built on arrays.