Skip to main content
eLearner.app
Module 4 · Lesson 1 of 516/50 in the course~8 min
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

Go
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 = 4

The zero value of an array is an array of the declared length with every element at its zero value:

Go
var nums [5]int  // [0 0 0 0 0]

Indexing and len

Go
a := [3]int{10, 20, 30}
fmt.Println(a[0])      // 10
a[1] = 99
fmt.Println(len(a))    // 3

Out-of-range access causes a runtime panic (not a silent undefined like in C).

Length is part of the type

Go
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:

Go
a := [3]int{1, 2, 3}
b := a               // copy
b[0] = 99
fmt.Println(a[0])    // 1 — a is unchanged

The 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]byte for 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

Exercise#go.m4.l1.e1
Attempts: 0Loading…

Declare a as an array of 3 ints with values 10, 20, 30 and print its length.

Loading editor…
Show hint

Array literal: `[3]int{a, b, c}`.

Solution available after 3 attempts

Exercise#go.m4.l1.e2
Attempts: 0Loading…

Declare b as an array of 5 ints (all zero) and assign 99 to position 2.

Loading editor…
Show hint

`var b [5]int` starts as [0 0 0 0 0].

Solution available after 3 attempts

Quiz#go.m4.l1.e3
Ready

Are [3]int and [4]int the same type?

Go
var a [3]int
var b [4]int
// a = b ?
Answer options

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.