๐Ÿ“ฆArraysLESSON

Arrays

Arrays are Go's fixed-length sequences. Unlike slices, the length is part of the type โ€” [3]int and [4]int are entirely distinct types and are not interchangeable.

Declaring Arrays

The type syntax is [n]Type where n is a compile-time constant:

Go zero-initializes every element, so you always get a predictable starting state without explicit initialization.

Array Literals

Use a composite literal to declare and initialize at once:

You can also let the compiler count the elements with ...:

Indexing and Length

Elements are accessed with zero-based indices. len always returns the declared size โ€” it is constant for a given array type:

Because the length is baked into the type, len on an array is a compile-time constant โ€” the runtime never needs to look it up.

Value Semantics โ€” Assignment Copies

This is the most important behavioral difference from slices. Assigning one array to another copies every element:

The same applies when passing an array to a function โ€” the callee receives an independent copy. Modifying it has no effect on the caller's original. This contrasts sharply with slices, which hold a pointer to a backing array and therefore exhibit reference semantics.

Arrays as the Backing Store for Slices

Every slice in Go is a three-field descriptor โ€” a pointer, a length, and a capacity โ€” that references a region of an underlying array. When you create a slice from an array, both share the same memory:

Understanding this relationship makes slice behavior predictable. The upcoming Slices lesson builds directly on this foundation.

When to Use Arrays

Because arrays are value types with a fixed size, they shine in specific contexts where that predictability matters:

  • Cryptographic digests โ€” [32]byte for a SHA-256 hash; the fixed size is part of the API contract.
  • Fixed-size buffers โ€” e.g., reading exactly 512 bytes at a time from a file.
  • Pixel and color data โ€” [4]uint8 for RGBA channels avoids allocation overhead.
  • Small lookup tables โ€” a [12]string for month names is clearer and cheaper than a slice.

For variable-length collections, prefer slices. Reach for an array when the count is a known constant that belongs in the type.

Knowledge Check

In Go, are `[3]int` and `[4]int` the same type?

What happens when you assign one array to another in Go?

What does `len` return for `var a [7]float64`?