Arrays and slices

14 min read go
Course contents (17 lessons)
  1. Getting started with Go
  2. Installing Go 1.25 and your first program
  3. Variables, types and constants
  4. Control flow: if, for and switch
  5. Functions, multiple returns and defer
  6. Slices and maps
  7. Arrays and slices
  8. Maps and working with strings
  9. Structs, methods and interfaces
  10. Structs, methods and pointers
  11. Interfaces
  12. Errors, packages and generics
  13. Error handling the Go way
  14. Packages and modules
  15. Generics
  16. Concurrency
  17. Goroutines and channels
  18. select, timeouts and context
  19. Mutexes, sync and the race detector
  20. Testing
  21. Testing and benchmarks
  22. Building and shipping a service
  23. Building an HTTP JSON API with net/http
  24. Building and deploying a Go service

Arrays exist, but you will use slices

An array in Go has a fixed length that is part of its type: [3]int and [4]int are different types. You rarely use arrays directly. The type you use all the time is the slice, a flexible view onto an array that can grow.

var scores [3]int              // [0 0 0], fixed size
names := []string{"Ali", "Sara"} // a slice: no number in the brackets

Working with slices

package main

import (
	"fmt"
	"slices"
)

func main() {
	tasks := []string{"buy milk", "pay bill"}
	tasks = append(tasks, "call plumber")
	tasks = append(tasks, "renew passport", "book tickets")

	fmt.Println(tasks, len(tasks))
	fmt.Println(tasks[1:3])  // [pay bill call plumber]
	fmt.Println(tasks[:2])   // [buy milk pay bill]
	fmt.Println(tasks[3:])   // [renew passport book tickets]

	// remove the item at index 1
	tasks = slices.Delete(tasks, 1, 2)
	fmt.Println(tasks)

	amounts := []int{1200, 450, 3100, 780}
	slices.Sort(amounts)
	fmt.Println(amounts, slices.Max(amounts), slices.Contains(amounts, 450))

	// make: length 0, capacity 10
	buf := make([]int, 0, 10)
	for i := range 5 {
		buf = append(buf, i*i)
	}
	fmt.Println(buf, len(buf), cap(buf))
}

Output:

[buy milk pay bill call plumber renew passport book tickets] 5
[pay bill call plumber]
[buy milk pay bill]
[renew passport book tickets]
[buy milk call plumber renew passport book tickets]
[450 780 1200 3100] 3100 true
[0 1 4 9 16] 5 10

Length and capacity

A slice has three parts: a pointer to an array, a length (how many elements it shows) and a capacity (how many fit before the array is full). len(s) and cap(s) give the last two. When you append and there is room, the element goes into the existing array. When there is no room, Go allocates a bigger array, copies the elements across and returns a slice pointing to the new array. That is why you must always use the result: tasks = append(tasks, x). Calling append(tasks, x) alone and ignoring the result is a compile error, and for good reason.

make([]int, 0, 10) creates a slice with length 0 and capacity 10. If you know roughly how many items you will add, giving a capacity up front avoids repeated reallocation. This is a simple and effective optimisation.

The shared array trap

Here is the behaviour that surprises almost everyone. A sub-slice shares the same array as the original.

original := []int{1, 2, 3, 4, 5}
part := original[1:3]     // [2 3]
part[0] = 99
fmt.Println(original)     // [1 99 3 4 5]  - changed!

part = append(part, 100)  // capacity allows it: overwrites original[3]
fmt.Println(original)     // [1 99 3 100 5]

Slicing does not copy. Both slices view the same memory, so a write through one is visible through the other. Even worse, appending to part can overwrite elements of original if there is spare capacity. I lost an afternoon to this once, when a function that "returned the first ten results" quietly overwrote the caller's data later.

When you need an independent copy, make one on purpose:

independent := slices.Clone(part)     // or: append([]int(nil), part...)
dst := make([]int, len(part))
n := copy(dst, part)                  // copy returns the count copied

You can also limit capacity with a full slice expression, original[1:3:3], so that an append must allocate a new array.

nil slices

A slice that was never initialised is nil with length 0. It works fine with len, range and append. You do not need to check for nil before appending. This is why var results []string is idiomatic as a starting point.

The slices package

Go 1.21 added the slices package, which saves you from writing helpers over and over: slices.Sort, slices.SortFunc, slices.Contains, slices.Index, slices.Reverse, slices.Max, slices.Min, slices.Equal, slices.Insert, slices.Delete and slices.Clone. Use them. Note that Go 1.22 changed Delete to zero the removed tail elements, which avoids a memory leak for slices of pointers.

Sorting with a custom rule uses slices.SortFunc and a comparison function that returns a negative number, zero or a positive number:

type Item struct {
	Name  string
	Price int
}

items := []Item{{"tea", 120}, {"rice", 280}, {"salt", 60}}
slices.SortFunc(items, func(a, b Item) int {
	return a.Price - b.Price
})

Slices of slices

You can build a table with a slice of slices: grid := make([][]int, 3), and then each row needs its own make. The inner slices do not exist until you create them, and indexing a nil inner slice panics.

Common mistakes

  • Ignoring append's result. The new slice header is returned and must be stored.
  • Assuming a sub-slice is a copy. It is a view. Clone when you need independence.
  • Index out of range. Reading s[len(s)] panics at run time with index out of range. Check lengths before indexing.
  • Holding a tiny slice of a huge array. A small sub-slice keeps the whole array alive in memory. Clone it if the big one should be freed.
  • Using make with a length, then appending. make([]int, 5) already holds five zeros. append adds the sixth. You usually want make([]int, 0, 5).

Try it yourself

Write a function filterAbove(values []int, limit int) []int that returns a new slice with only the values above the limit, without changing the input. Test that the original is unchanged. Then write a function that returns the first three elements of a slice as an independent copy and prove with a test in main that changing the copy does not touch the original.

go
package main

import (
	"fmt"
	"slices"
)

func main() {
	tasks := []string{"buy milk", "pay bill"}
	tasks = append(tasks, "call plumber")
	tasks = append(tasks, "renew passport", "book tickets")

	fmt.Println(tasks, len(tasks))
	fmt.Println(tasks[1:3])  // [pay bill call plumber]
	fmt.Println(tasks[:2])   // [buy milk pay bill]
	fmt.Println(tasks[3:])   // [renew passport book tickets]

	// remove the item at index 1
	tasks = slices.Delete(tasks, 1, 2)
	fmt.Println(tasks)

	amounts := []int{1200, 450, 3100, 780}
	slices.Sort(amounts)
	fmt.Println(amounts, slices.Max(amounts), slices.Contains(amounts, 450))

	// make: length 0, capacity 10
	buf := make([]int, 0, 10)
	for i := range 5 {
		buf = append(buf, i*i)
	}
	fmt.Println(buf, len(buf), cap(buf))
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account