Fixed-Size Arrays

Fixed-Size Arrays in Go: A field technician's instrument case has a foam insert cut for exactly six instruments.

The Analogy: The Foam-Cut Instrument Case

A field technician's instrument case has a foam insert cut for exactly six instruments. Six is not a number written on a label that somebody could change with a marker pen; six is the shape of the foam. If the team buys a seventh instrument, nobody "extends" the case. They buy a different case, because a case cut for eight is a physically different object from a case cut for six, and the pair of them are not interchangeable in any sense that matters.

Go arrays work exactly like that, and this is the part that surprises people arriving from almost any other language: the length is part of the type. [6]float64 and [8]float64 are two different types, as unrelated to each other as int and string. A function declared to take a [6]float64 will not accept a [8]float64, and the compiler rejects it before your program ever runs. There is no resizing, no append, no growth. The size is fixed at compile time and it is checked at compile time.

The second property follows from the case being a physical object. Hand somebody the case and you have handed over the case itself, all six slots and everything in them. In Go, an array is a value. Assigning one array to another copies every element. Passing one to a function copies every element into the function's own parameter, so the function can rearrange its copy all it likes and yours is untouched. Most languages make their arrays references, so this is the single most common source of confusion when reading Go array code: nothing here is shared unless you explicitly share a pointer to it.

So why does Go bother, when every day-to-day Go program uses slices instead? Because some sizes genuinely never change, and encoding that in the type is free correctness. A SHA-256 digest is always thirty-two bytes. An IPv4 address is always four. A lookup table indexed by a byte always has two hundred and fifty-six entries. For those, an array is smaller, faster, comparable with ==, usable as a map key, and impossible to accidentally resize. Arrays are also the thing slices are built on top of, so you cannot really understand the next lesson without this one.


Syntax or Core Structure

Five ways to write an array, then a demonstration that assignment copies and that arrays compare with ==.

package main

import "fmt"

func main() {
    var zero [4]int                          // every element is the zero value
    primes := [5]int{2, 3, 5, 7, 11}         // explicit length
    inferred := [...]string{"gb", "de", "fr"} // compiler counts for you
    sparse := [6]int{2: 30, 5: 60}           // indexed elements, rest are zero

    fmt.Printf("%-10s %v len %d\n", "zero:", zero, len(zero))
    fmt.Printf("%-10s %v len %d\n", "primes:", primes, len(primes))
    fmt.Printf("%-10s %v len %d\n", "inferred:", inferred, len(inferred))
    fmt.Printf("%-10s %v len %d\n", "sparse:", sparse, len(sparse))

    copied := primes
    copied[0] = 999
    fmt.Printf("%-8s %v\n", "primes:", primes)
    fmt.Printf("%-8s %v\n", "copied:", copied)

    fmt.Println("equal:", [2]int{1, 2} == [2]int{1, 2})
}

Output:

zero:      [0 0 0 0] len 4
primes:    [2 3 5 7 11] len 5
inferred:  [gb de fr] len 3
sparse:    [0 0 30 0 0 60] len 6
primes:  [2 3 5 7 11]
copied:  [999 3 5 7 11]
equal: true

copied := primes copied all five integers. Writing 999 into copied[0] left primes exactly as it was, which is the whole difference between an array and a slice in one line. [...]string{...} is not a special "dynamic" form: the compiler counts the elements and the type is [3]string, fixed forever. And the length must be a constant expression, so [n]int where n is a variable does not compile.


Technical Depth: The Length Is In the Type

Type identity is the rule everything else follows from.

ExpressionTypeAssignable to [3]int?
[3]int{1, 2, 3}[3]intYes
[4]int{1, 2, 3, 4}[4]intNo, different type
[...]int{1, 2, 3}[3]intYes
[]int{1, 2, 3}[]intNo, that is a slice
&[3]int{1, 2, 3}*[3]intNo, that is a pointer

Because the length is static, len(arr) is a compile-time constant. It can appear where a constant is required, such as another array's length, and it costs nothing at run time. cap(arr) equals len(arr) and never changes.

Value Semantics and Their Cost

OperationWhat happens
b := aEvery element is copied
f(a)Every element is copied into the parameter
return aEvery element is copied to the caller
f(&a)Eight bytes are copied; f can mutate your array
a[i] = x inside range aLater iterations do not see it; range copied the array

The copy is a real memory copy, so a [1024]int parameter moves eight kilobytes on every call. This is the reason slices exist and the reason *[N]T parameters show up in cryptographic code, where the size must stay in the type but copying would be wasteful. Note that a pointer to an array can be indexed directly: p[0] works without writing (*p)[0], and len(p) works too.

Comparability and Map Keys

An array of comparable elements is comparable, and == compares element by element in order.

Element type== works?Usable as a map key?
[4]int, [32]byte, [2]stringYesYes
[3]struct{X, Y int}YesYes
[2][]intNo, slices are uncomparableNo
[2]map[string]intNoNo

This is why sha256.Sum256 returns a [32]byte rather than a []byte: the array can go straight into a map[[32]byte]bool for deduplication, while a slice would have to be converted to a string first. It is one of the few places where the array form is the ergonomic choice as well as the fast one.

Memory Layout

An array is nothing but its elements, laid out contiguously with no header at all. A slice is a three-word header pointing at an array somewhere else.

Valueunsafe.Sizeof on a 64 bit platform
[4]int3216 bytes, the elements and nothing else
[4]int6432 bytes
[]int3224 bytes: pointer, length, capacity
[256]int2048 bytes
*[256]int8 bytes

Contiguity is why arrays are cache-friendly and why [3][4]int is a genuine two-dimensional block of twelve integers in a row. A [][]int of the same shape is three slice headers pointing at three separately allocated rows, which means three extra allocations, worse locality, and rows that can each have a different length. When the shape is genuinely rectangular and known, the array form is both faster and more honest.

Bounds Checking

IndexWhen it is caught
Constant, out of rangeCompile time; the build fails
Variable, out of rangeRun time panic: index out of range [7] with length 5
A byte into a [256]TNever out of range, and the compiler removes the check

That last row is a genuinely useful trick rather than trivia. If you index a 256-element array with a value whose type is byte, the compiler can prove the index is in range and emits no check at all, which is why byte-keyed lookup tables are the fastest thing in Go for this kind of work.


Real World Example: A Byte Histogram Content Sniffer

Deciding whether a file is text or binary is a job with a naturally fixed domain: a byte has exactly two hundred and fifty-six possible values, today and forever. That makes [256]int the correct container, not a map[byte]int, and it lets the counter be indexed by the byte itself with no bounds check and no allocation.

package main

import "fmt"

// Profile is comparable because [256]int is comparable.
type Profile struct {
    counts [256]int
    total  int
}

func profile(data []byte) Profile {
    var p Profile
    for _, b := range data {
        p.counts[b]++ // b is a byte, so this index can never be out of range
        p.total++
    }
    return p
}

// isText rejects any NUL byte, then allows up to 5 percent control bytes.
func (p *Profile) isText() bool {
    if p.counts[0] > 0 {
        return false
    }
    control := 0
    for b := 1; b < 32; b++ {
        if b == '\t' || b == '\n' || b == '\r' {
            continue
        }
        control += p.counts[b]
    }
    return p.total == 0 || control*100 <= p.total*5
}

// topByte reports the most common byte, lowest value winning a tie.
func (p *Profile) topByte() (byte, int) {
    best, count := byte(0), -1
    for i := range p.counts {
        if p.counts[i] > count {
            best, count = byte(i), p.counts[i]
        }
    }
    return best, count
}
func main() {
    samples := []struct {
        name string
        data []byte
    }{
        {"plain", []byte("hello world\n")},
        {"tabs", []byte("a\tb\tc\n")},
        {"nul", []byte{'h', 'i', 0, 'x'}},
        {"escapes", []byte{0x1b, '[', '3', '1', 'm', 'r', 'e', 'd'}},
        {"empty", nil},
    }

    for _, s := range samples {
        p := profile(s.data)
        b, n := p.topByte()
        fmt.Printf("%-8s bytes=%2d text=%-5t top=%q x%d\n",
            s.name, p.total, p.isText(), b, n)
    }

    a := profile([]byte("abc"))
    c := profile([]byte("cba"))
    fmt.Println("abc and cba have identical profiles:", a == c)
}

Output:

plain    bytes=12 text=true  top='l' x3
tabs     bytes= 6 text=true  top='\t' x2
nul      bytes= 4 text=false top='\x00' x1
escapes  bytes= 8 text=false top='\x1b' x1
empty    bytes= 0 text=true  top='\x00' x0
abc and cba have identical profiles: true

Four properties make [256]int the right choice here, and a map[byte]int the wrong one. The domain is closed, so there is nothing a map's flexibility could buy. The zero value is already a working counter, so var p Profile needs no initialization at all, no make, no constructor. Indexing with a byte cannot be out of range, so p.counts[b]++ has no failure mode and the compiler emits no bounds check. And there is no allocation and no hashing on the hot path, so counting a megabyte of input is one increment per byte.

The cost side is equally concrete. Profile is 2056 bytes on a 64 bit platform: 2048 for the counts plus 8 for the total. That is why isText and topByte take *Profile rather than Profile; a value receiver would copy two kilobytes on every call, and topByte is the kind of method a caller might invoke in a loop. It is also why topByte is written for i := range p.counts and not for i, n := range p.counts. With only the index variable, the specification lets the compiler skip evaluating the array value at all; ask for the element too and you have asked for a copy of the whole array.

a == c compares all two hundred and fifty-seven fields in one expression, and the answer is true because abc and cba really do have identical byte histograms. That is not a flaw in the comparison, it is what a histogram means: it throws ordering away and keeps only the counts. Because Profile is comparable, it can also be a map key, which is how you would build a cache of "have I seen this distribution before" without writing a single line of comparison code.

What a production sniffer adds is bounded reading rather than a different data structure. net/http.DetectContentType looks at the first five hundred and twelve bytes and matches signature tables; a text-versus-binary check usually caps at a few kilobytes, because a NUL byte in the first block is decisive and a file that is text for eight kilobytes is text. The array is what makes that streaming-friendly: feed the same Profile chunk after chunk and nothing reallocates, because there is nothing to reallocate. The five percent threshold is a heuristic and should be a named constant with a comment explaining where the number came from.


Common Mistakes

  1. Expecting [5]int and [6]int to be interchangeable. They are different types. A function signature commits to one length forever, which is usually the sign you wanted a slice.
  1. Passing a large array to a function and wondering where the time went. Every element is copied. Pass *[N]T or a slice.
  1. Mutating elements inside for _, v := range arr. v is a copy and range copied the array as well. Index instead.
  1. Trying [n]int with a variable n. The length must be a constant expression. Use make([]int, n).
  1. Reaching for append on an array. append takes a slice. Convert with arr[:] first, and understand that the result may stop sharing the array once it grows.
  1. Assuming [...]T{...} means dynamic. It only means "count the literal for me"; the resulting type has a fixed length like any other.
  1. Using map[byte]int for a byte histogram. It hashes, allocates, and iterates in random order, all to model a domain that a 256-element array covers exactly.
  1. Building a rectangular grid as [][]int out of habit. If the shape is fixed, [R][C]int is one contiguous block instead of R allocations, and rows cannot get out of step.
  1. Forgetting that a copy of an array containing slices is shallow. [2][]int copies two slice headers, and both copies still point at the same backing data.

Best Practices

  • Use an array when the length is a fact about the problem, such as 32 bytes of digest or 4 bytes of address, and a slice for everything else.
  • Index lookup tables with the value itself when the domain is a byte or a small enum; it is the fastest and safest form of lookup Go has.
  • Take *[N]T for anything large enough that copying matters, and remember you can still index and len the pointer directly.
  • Rely on the zero value: var counts [256]int is ready to use with no initialization step.
  • Prefer for i := range arr over for i, v := range arr when the array is large and you only need the index.
  • Use array types as map keys when you need to key on fixed-size binary data, instead of converting to a string.
  • Choose [R][C]T over [][]T for genuinely rectangular data, and document the meaning of each dimension.
  • Convert with arr[:] at the boundary where a slice is expected, rather than storing both forms.

Practice Exercises

  1. The Type Wall: Write a function taking a [4]int and call it with a [4]int, a [5]int, and a []int. Record all three compiler results, then change the parameter to []int and note which of the three calls now work and what you gave up.
  1. Prove the Copy: Write a function that sorts its [8]int parameter in place and prints the result. Call it and then print the caller's array. Change the parameter to *[8]int, repeat, and explain both outcomes in one sentence each.
  1. Extend the Sniffer: Add a method reporting the number of distinct byte values seen and another reporting the proportion of printable ASCII. Run it against at least four inputs including an empty one. Then change the receivers from *Profile to Profile and describe what that costs.
  1. Grid Two Ways: Build a 3 by 4 grid of integers as [3][4]int and as [][]int. Fill both, copy both to a second variable, mutate the copy, and print the originals. Explain why one original changed and the other did not.