Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 147 ยท Collections

Arrays

Learn Go arrays - why the size is part of the type, value semantics and copying, [...]T literals, indexing and bounds checks, comparing arrays, multi-dimensional arrays and when to use them.

An array is a numbered, fixed-length sequence of values that all have the same type. If you've used arrays in C, Java or JavaScript, Go's version will feel familiar at first and then surprise you in two ways: the length is part of the type, and arrays are values, so assigning one to another copies every element.

You'll rarely use arrays directly in everyday Go; slices are the workhorse. But slices are built on top of arrays, so understanding arrays makes slices, copying and memory behavior much easier to follow. This lesson covers declaring and initializing arrays, indexing, bounds checks, comparison, copying, multi-dimensional arrays and the places where arrays really are the right tool.

Declaring arrays

The type of an array is written [N]T: a length in square brackets, then the element type. Every element starts at the zero value of T, so there is no uninitialized memory:

Go Declaring arrays and zero values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

len gives the number of elements. The length must be a constant known at compile time: [n]int with a variable n is not an array type (use a slice with make for runtime sizes).

Array literals

Use a composite literal to supply values. Write the length yourself, or let the compiler count with ...:

Go Array literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

[...]T{...} is a literal, not a type: the result is a normal [5]string. The index: value form is handy for tables where most entries are zero, and it also works with named constants as indexes, for instance an array indexed by an enum created with iota.

Supplying more values than the length is a compile error, as is a constant index outside the array:

Go Too many values (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler stops with ./main.go:6:26: index 3 is out of bounds (>= 3), pointing at the fourth value. Go catches this mistake before the program ever runs.

Indexing and bounds checks

Elements are numbered from 0. Read and write them with a[i]; range walks index and value:

Go Reading, writing and ranging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go checks every index. A constant index that is out of range fails at compile time; a variable index that is out of range panics at runtime instead of reading random memory like C does:

Go Index out of range at runtime (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program prints the first line and then dies with panic: runtime error: index out of range [3] with length 3, a goroutine 1 [running]: trace pointing to main.go:9 and exit status 2. Negative indexes are never allowed. If you want to handle the problem instead of crashing, check i >= 0 && i < len(a) first.

Arrays are values

In Go, an array variable holds the whole array, not a pointer to it. Assigning or passing an array copies all of its elements:

Go Assignment copies the whole array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Changing clone leaves original alone, and reset cannot change its argument. To let a function modify the caller's array, pass a pointer (*[3]int) or, more commonly, a slice. Passing huge arrays by value is slow, because each call copies them; that is one reason slices are preferred. See Pointers, Values and Functions.

The length is part of the type

[3]int and [4]int are different types. You can't assign one to the other, compare them or pass one where the other is expected:

Go Different lengths are different types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You'll see ./main.go:9:6: cannot use b (variable of type [4]int) as [3]int value in assignment. This is why a function taking [3]int is almost useless as a general utility, and why Go introduced slices, which have one type for every length.

Comparing arrays

Arrays are comparable with == and != as long as their element type is comparable. Two arrays are equal when every pair of elements is equal:

Go Comparing and using arrays as map keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because arrays are comparable, [2]int works nicely as a grid coordinate map key. Slices cannot do this: they aren't comparable. (A defined type like Point [2]int is fine, see Defined Types and Type Aliases.)

Multi-dimensional arrays

Go has no special syntax for matrices; you make an array of arrays:

Go A 3 by 4 grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

grid is an array of 3 elements, each of which is a [4]int, so grid[1][2] means row 1, column 2. Inner literal types may be omitted, as in board. The inner arrays are laid out one after another in memory, in a single contiguous block.

Arrays and range

range over an array copies the array first when you use the value variable, because arrays are values. For large arrays this can matter; range over a slice of the array (or a pointer to it) to avoid the copy:

Go Range works on a copy of the array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first loop prints 2 3 for the last element even though the array was changed, because it iterates a copy. The loop over &nums sees 100. Details are in Ranging Over Collections.

When to use arrays

Because slices are more flexible, reach for arrays only when a fixed size is meaningful:

  • Small fixed-size data: coordinates [2]float64, RGB colors [3]uint8, IPv4 addresses [4]byte.
  • Hash results: sha256.Sum256 returns a [32]byte, and arrays make it comparable and usable as a map key.
  • Lookup tables indexed by a small enum.
  • Avoiding allocations: an array local to a function can stay on the stack.

Everywhere else, use a slice. You can always turn an array into a slice with the slicing expression arr[:], which shares the array's memory; the next lesson on Slices shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var a [3]int contain?

    Go always initializes variables to their zero value, so each int element is 0.
  2. 2. After b := a where a is an array [3]int, what does b[0] = 9 do to a?

    Arrays are values, so assignment copies every element. a and b are separate arrays.
  3. 3. Which statement is true about [3]int and [4]int?

    The length is part of an array's type, so arrays of different lengths are unrelated types.
  4. 4. What happens with x := [3]int{1, 2, 3}; i := 5; fmt.Println(x[i])?

    i is a variable, so the check happens at run time and fails with a panic. A constant index like x[5] would have been a compile error.
  5. 5. What does [...]string{"a", "b", "c"} create?

    The ... lets the compiler count the elements. The result has the concrete array type [3]string.

Summary

  • An array is a fixed-length sequence of one element type, written [N]T; the length is part of the type and must be a constant.
  • Elements start at their zero value; literals can use [...]T{...} for the length and index: value pairs for sparse data.
  • Indexes start at 0; constant out-of-range indexes fail at compile time and variable ones panic at run time.
  • Arrays are values: assignment and function arguments copy every element, and range iterates over a copy.
  • Arrays of comparable elements support == and can serve as map keys.
  • Multi-dimensional arrays are arrays of arrays stored contiguously.
  • Prefer slices in most code, and use arrays for small fixed-size data, hashes and lookup tables.

Next: Slices shows the flexible, growable view of arrays that Go programmers use every day.