TExcelTAD
Home › Go › Go Slices

Go Slices

A slice is a flexible, growable view of a sequence of elements. It is the list type you will use in almost every Go program. The type is written []T — like an array type but without a length.

Creating slices

go · try it yourself
package main

import "fmt"

func main() {
	fruits := []string{"apple", "pear", "plum"} // slice literal
	var empty []int                             // nil slice, length 0
	buffer := make([]int, 3)                    // length 3, all zeros
	reserve := make([]int, 0, 10)               // length 0, capacity 10

	fmt.Println(fruits, len(fruits))
	fmt.Println(empty, len(empty), empty == nil)
	fmt.Println(buffer, len(buffer))
	fmt.Println(reserve, len(reserve), cap(reserve))
}
[apple pear plum] 3
[] 0 true
[0 0 0] 3
[] 0 10

How a slice works: pointer, length, capacity

A slice does not store its elements itself. It is a small header with three fields:

Field Meaning Read with
pointer where the first element lives in an underlying array —
length how many elements the slice currently contains len(s)
capacity how many elements fit before a new array is needed cap(s)

Slicing: s[low:high]

The expression a[low:high] creates a slice of the elements from index low up to, but not including, high. Either bound may be omitted.

go · try it yourself
package main

import "fmt"

func main() {
	letters := []string{"a", "b", "c", "d", "e", "f"}

	fmt.Println(letters[1:4]) // b c d
	fmt.Println(letters[:2])  // first two
	fmt.Println(letters[3:])  // from index 3 to the end
	fmt.Println(letters[:])   // everything

	part := letters[1:3]
	fmt.Println(len(part), cap(part))
}
[b c d]
[a b]
[d e f]
[a b c d e f]
2 5

The capacity of part is 5 because the underlying array continues from index 1 to the end.

Slices share memory

Because slices point into an array, two slices can see the same elements. Changing one changes what the other sees:

go · try it yourself
package main

import "fmt"

func main() {
	nums := []int{10, 20, 30, 40}
	middle := nums[1:3]

	middle[0] = 99
	fmt.Println(nums)   // the original changed too!
	fmt.Println(middle)
}
[10 99 30 40]
[99 30]

This also means that passing a slice to a function is cheap (only the header is copied) and the function can modify the caller's elements.

Growing with append

append adds elements to the end and returns the updated slice. Always assign the result back, because if the capacity runs out, append allocates a new, larger array and copies the elements over.

go · try it yourself
package main

import "fmt"

func main() {
	var tasks []string
	tasks = append(tasks, "write")
	tasks = append(tasks, "test", "ship")
	fmt.Println(tasks, len(tasks))

	more := []string{"celebrate", "rest"}
	tasks = append(tasks, more...) // ... spreads a slice
	fmt.Println(tasks)

	// remove the element at index 1
	tasks = append(tasks[:1], tasks[2:]...)
	fmt.Println(tasks)
}
[write test ship] 3
[write test ship celebrate rest]
[write ship celebrate rest]

Copying a slice

To get an independent copy, make a new slice and use the built-in copy(dst, src), which copies min(len(dst), len(src)) elements and returns that number.

go · try it yourself
package main

import (
	"fmt"
	"slices"
)

func main() {
	src := []int{1, 2, 3}
	dst := make([]int, len(src))
	n := copy(dst, src)
	dst[0] = 100

	fmt.Println(n, src, dst)

	clone := slices.Clone(src) // the modern shortcut (Go 1.21+)
	clone[2] = 7
	fmt.Println(src, clone)
	fmt.Println(slices.Contains(src, 2), slices.Index(src, 3))
}
3 [1 2 3] [100 2 3]
[1 2 3] [1 2 7]
true 2
Operation Code
length / capacity len(s), cap(s)
add to end s = append(s, x)
join two slices s = append(s, other...)
independent copy slices.Clone(s) or make + copy
sort slices.Sort(s)
search slices.Contains(s, x), slices.Index(s, x)

Tip: If you know roughly how many elements you will add, create the slice with make([]T, 0, n). append then never has to reallocate.

Test yourself

What does s[2:5] contain?

  1. Elements at indexes 2, 3, 4 and 5
  2. Elements at indexes 2, 3 and 4
  3. Elements at indexes 3, 4 and 5
  4. Five elements starting at 2

Why must you write s = append(s, x) instead of just append(s, x)?

  1. Style only
  2. append may return a slice pointing to a new array, and the result must be used
  3. append modifies s in place and returns nothing
  4. To avoid a panic

After b := a[0:2]; b[0] = 5, what is a[0]?

  1. Unchanged
  2. 5
  3. 0
  4. Compile error