Slices, maps and strings · 3 MIN READ

The length is part of an array's type

Write a function that takes [4]int and returns [3]int.

The Tour's "Arrays" page is the one people skip because slices are what you use. Then a function signature says [32]byte and the compiler refuses a [16]byte. The length is in the type: [4]int and [3]int are as different as int and string.

An array is a value. Assigning it copies every element. A slice is a header pointing at an array, which is why two slices can share memory and two arrays never do unless you pass a pointer. The conversion is one way and explicit: s := a[:] views the array; there is no implicit [n]T from a slice of the wrong length.

SEE THE IDEA

Array length belongs to its type

  1. 01

    Fixed value

    go
    [3]int

    Exactly three elements

  2. 02

    Different type

    go
    [4]int

    Not assignable as [3]int

  3. 03

    Flexible view

    go
    []int

    A slice refers to backing storage

Arrays are values; slices describe a view over elements.

In practice

Use arrays when a fixed length is part of the contract, such as a digest. Array assignment copies every element. Slicing an array creates a view of it; converting or copying into another array is a separate operation with its own bounds requirements.

Watch out

Passing an array by value copies it. A slice parameter does not copy its backing elements.

Official reference ↗

Work through the exercise

go
package main

// FirstThree returns the first three elements as an array, not
// a slice. The length has to be in the type.
func FirstThree(values [4]int) [3]int {
	return [3]int{}
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.