Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Go Slices Explained: Length, Capacity, Append and Copy

Create and reslice slices in Go, see how length and capacity differ, and avoid accidentally changing a shared backing array.

Table of Contents

A slice in Go describes a sequence of elements stored in a backing array. Write its type as []T, such as []int. A slice has a length and a capacity, and you can use append to grow it.

What is Slice in Golang? Picture 1

Slice an array

Use a[low:high]. The result includes low and excludes high. The first index within the new slice is zero.

package main

import "fmt"

func main() {
    a := [5]int{1, 2, 3, 4, 5}
    s := a[1:4]
    fmt.Println(s, len(s), cap(s)) // [2 3 4] 3 4
    s[0] = 20
    fmt.Println(a) // [1 20 3 4 5]
}

What length and capacity measure

len(s) counts elements you can access now. cap(s) measures space from the slice’s starting point to the end of its available backing storage. In the example, index 4 of the array is outside the slice’s length, but within its capacity.

Create, append to, or copy a slice

var none []int           // nil, length 0
values := []int{1, 2, 3} // literal
zeros := make([]int, 3, 8) // 3 zero values, capacity 8
values = append(values, 4, 5)
independent := make([]int, len(values))
copy(independent, values)

Always keep the result of append. It can reuse the backing array when there’s room or allocate another one. That matters when two slices refer to the same storage. For an independent copy, allocate a destination with the right length and use copy, as shown above.

See the Go project’s slice guide for diagrams of the relationship between a slice and its backing array.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.