Arrays
Go arrays are fixed-length and pass by value. Slices (the dynamically-resizable wrapper around them) are what you actually use 99% of the time, but understanding arrays matters — especially for performance and embedded uses.
Fixed-size arrays + when they help
EXAMPLE
package main
import "fmt"
func main() {
// 1) Declaration
var a [5]int // zero-valued
b := [5]int{1, 2, 3, 4, 5} // literal
c := [...]int{1, 2, 3} // length inferred
d := [5]int{2: 99} // {0, 0, 99, 0, 0}
fmt.Println(a, b, c, d, len(b))
// 2) Arrays are VALUES — passing copies the whole thing
e := b
e[0] = 999
fmt.Println(b[0], e[0]) // 1 999 (no aliasing)
// 3) Element access + iteration
for i, v := range b {
fmt.Println(i, v)
}
// 4) Arrays as map keys / struct fields work (no slice issues)
type Vec3 = [3]float64
var origin Vec3 // {0, 0, 0}
var translate Vec3 = [3]float64{1, 2, 3}
counts := map[[2]int]int{}
counts[[2]int{3, 4}]++
// 5) Convert to / from a slice
s := b[:] // slice viewing the whole array
s[0] = 100
fmt.Println(b[0]) // 100 — slice and array share memory
// 6) When to actually use an array (not a slice)
// • Inside a struct, when the field is a known fixed size
// • As a map key (slices CAN'T be map keys)
// • Hot-path inner loops where the size is constant
// • Cryptographic / binary protocols (fixed-length tokens, MAC outputs)
}
Why it matters
Reach for [N]T only when N is genuinely fixed at compile time. For everything else — growth, dynamic indexing, passing around — use a slice ([]T).
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…