Arrays
Prerequisites: Loops
An array holds a fixed number of values of one type. The
length is part of the type: [3]int and [4]int are different,
incompatible types.
Syntax
var scores [3]int // [0 0 0] — zero values
primes := [5]int{2, 3, 5, 7, 11} // array literal
days := [...]string{"Mon", "Tue"} // length counted for you: [2]string
Example
package main
import "fmt"
func main() {
var scores [3]int
scores[0] = 90
scores[2] = 75
fmt.Println(scores, len(scores))
primes := [5]int{2, 3, 5, 7, 11}
copied := primes // copies all five values
copied[0] = 100
fmt.Println(primes[0], copied[0])
total := 0
for _, p := range primes {
total += p
}
fmt.Println("sum:", total)
}
Expected output
[90 0 75] 3
2 100
sum: 28
Arrays are values: assigning one to another variable, or passing it to a function, copies every element. That's the key difference from slices, which you'll meet next.
In practice, arrays are used less often than slices — mainly when the size is truly fixed (like the 3 bytes of an RGB color). Most Go code reaches for slices instead.
Common mistakes
- Reading or writing past the end. With a constant index this is a
compile error (
invalid argument: index 3 out of bounds [0:3]); with a variable index the program panics at runtime. - Expecting an array to grow — it can't. Use a slice when the size changes.
Practice
Create an array of 4 temperatures, then use a loop to find and print the highest one.
Show solution
package main
import "fmt"
func main() {
temps := [4]int{21, 27, 19, 24}
highest := temps[0]
for _, t := range temps {
if t > highest {
highest = t
}
}
fmt.Println(highest) // 27
}