Go Tutorial · Data Structures · Lesson 13 of 30

Go Arrays and Slices

Fixed-size arrays, dynamic slices, append, slicing and capacity.

Arrays

An array has a fixed length that's part of its type — [3]int and [4]int are different types. You'll rarely use them directly.

Slices

A slice is a flexible view over an array — the list type you'll use everywhere:

Example 1
package main

import "fmt"

func main() {
	var fixed [3]int
	fixed[0] = 7
	fmt.Println(fixed, len(fixed))

	nums := []int{1, 2, 3}
	nums = append(nums, 4, 5)
	fmt.Println(nums, len(nums), nums[0], nums[len(nums)-1])

	scores := make([]int, 0, 10) // length 0, capacity 10
	scores = append(scores, 90)
	fmt.Println(scores, len(scores), cap(scores))
}

Output

[7 0 0] 3
[1 2 3 4 5] 5 1 5
[90] 1 10

Run this on your computer — see “Get Started” for setup.

Slicing shares memory

s[low:high] creates a new slice header over the same underlying array. Changing one changes the other — use copy or slices.Clone when you need independence:

Example 2
package main

import (
	"fmt"
	"slices"
)

func main() {
	base := []int{10, 20, 30, 40, 50}
	part := base[1:3]
	fmt.Println(part)
	part[0] = 999
	fmt.Println(base) // base changed too!

	independent := slices.Clone(base[1:3])
	independent[0] = 1
	fmt.Println(base[1], independent)
}

Output

[20 30]
[10 999 30 40 50]
999 [1 30]

Run this on your computer — see “Get Started” for setup.

The slices package

Go 1.21 added generic helpers: slices.Sort, slices.Contains, slices.Index, slices.Max, slices.Reverse:

Example 3
package main

import (
	"fmt"
	"slices"
)

func main() {
	names := []string{"zoe", "al", "mia"}
	slices.Sort(names)
	fmt.Println(names, slices.Contains(names, "al"), slices.Index(names, "zoe"))
	nums := []int{4, 9, 1}
	fmt.Println(slices.Max(nums), slices.Min(nums))
	slices.Reverse(nums)
	fmt.Println(nums)
}

Output

[al mia zoe] true 2
9 1
[1 9 4]

Run this on your computer — see “Get Started” for setup.

Test yourself

Which built-in adds elements to a slice?

  1. push
  2. add
  3. append
  4. insert
Show answer

Answer: append

Practice next