Module lessons (1/5)
Fixed-length arrays
In Go an array has a fixed length, baked into its type: [N]T.
It's a primitive rarely used directly in application code — you'll
almost always work with slices (next lesson), which are dynamic
views over arrays.
Still, understanding arrays well is essential: everything in Go is built on top of them.
Declaration and initialization
var a [3]int = [3]int{10, 20, 30}
b := [3]int{1, 2, 3} // inference with :=
c := [3]int{} // all zero: [0, 0, 0]
d := [...]int{1, 2, 3, 4} // length inferred = 4The zero value of an array is an array of the declared length with every element at its zero value:
var nums [5]int // [0 0 0 0 0]Indexing and len
a := [3]int{10, 20, 30}
fmt.Println(a[0]) // 10
a[1] = 99
fmt.Println(len(a)) // 3Out-of-range access causes a runtime panic (not a silent undefined like in C).
Length is part of the type
var a [3]int
var b [4]int
// a = b // ERROR: different types[3]int and [4]int are distinct types, even though both hold
int. This is why arrays are seldom passed to functions: you'd have to
hard-code the length into the parameter type.
Copy by value
Unlike slices (reference) and maps (reference), arrays are copied by value:
a := [3]int{1, 2, 3}
b := a // copy
b[0] = 99
fmt.Println(a[0]) // 1 — a is unchangedThe same applies when passing to a function: the function receives its own copy.
When to use arrays?
- Fixed-size buffers known at compile time (e.g.
[16]bytefor an MD5). - Composite map keys (slices are not "comparable", arrays are).
- Extreme performance (no indirection, cache-friendly).
For 99% of code: use slices.
Try it
Declare a as an array of 3 ints with values 10, 20, 30 and print its length.
Show hint
Array literal: `[3]int{a, b, c}`.
Solution available after 3 attempts
Declare b as an array of 5 ints (all zero) and assign 99 to position 2.
Show hint
`var b [5]int` starts as [0 0 0 0 0].
Solution available after 3 attempts
Are [3]int and [4]int the same type?
var a [3]int
var b [4]int
// a = b ?Recap
[N]T: fixed length, part of the type.- Zero value: every element at its zero value.
[...]int{...}lets the compiler infer the length.- Copy by value (including inside functions).
- Out-of-range = panic, not undefined.
- In practice, use slices, which are views over arrays.