Slices in Go
An overview of slices in Go covering type structure, creation, slicing, length and capacity, append, copy, nested slices, and shared underlying arrays
Arrays work well when you know exactly how many elements you need and that number never changes. Most programs, however, need collections that can grow and shrink as data arrives or leaves. That is the problem slices solve. A slice is a lightweight, flexible view into a contiguous sequence of elements, an abstraction built directly on top of arrays but without the fixed-size constraint.
How Slices Are Structured
A slice value is a tiny struct-like value with three fields: a pointer to an element of an underlying array, a length (the number of elements the slice currently exposes), and a capacity (how far it can grow without a new array). The underlying array may be shared among several slices, so modifying an element through one slice is visible through any other slice sharing that region. The zero value of a slice is nil, which behaves like an empty slice for most purposes but marshals to JSON as null, while a non-nil empty slice marshals as [].
package main
import "fmt"
func main() {
arr := [5]int{10, 20, 30, 40, 50}
s1 := arr[0:3] // len 3, cap 5
s2 := arr[1:4] // len 3, cap 4
s1[1] = 99
fmt.Println(s2[0]) // 99 - s1 and s2 share arr[1]
}
Creating Slices
You can create a slice with a literal ([]string{"Alice", "Bob"}), with make when you know the size but not the values (make([]int, 0, 10) reserves capacity without setting length), or by slicing an existing array or slice (arr[1:4]). Slicing never copies data: the new slice points into the same backing array.
Slice Expressions: Controlling What You See
The general form is s[low:high] or the full three-index form s[low:high:max]. The two-index version sets the capacity to the distance from low to the end of the underlying array. The three-index version restricts the capacity to max - low, which stops a later append on the sub-slice from overwriting elements that belong to other slices sharing the same array.
Length and Capacity: The Two Numbers That Rule Slices
Length (len) is the number of elements you can access by index without panicking; capacity (cap) is how far the slice can grow by re-slicing before it needs a new underlying array. Re-slicing changes the length, never the capacity. Indexing past the length panics even when the capacity is larger.
The append Built-in: Growing a Slice Dynamically
append adds elements to the end of a slice and always returns a new slice header, which you must capture: s = append(s, x). When there is spare capacity it reuses the backing array; when there is not, it allocates a larger one and copies the elements over. How much larger is an implementation detail of the runtime, not a rule of the language, so do not write code that depends on exact capacities.
The copy Built-in: Duplicating Elements Safely
copy(dst, src) copies elements from a source slice into a destination slice and returns the number copied, which is the minimum of len(dst) and len(src). It never changes the length of either slice and never allocates, so the destination must already have enough length. It handles overlapping slices correctly, so it can shift elements within the same slice.
Two-Dimensional and Nested Slices
A slice of slices ([][]T) represents grids and tables. Each inner slice is independent, so rows can have different lengths (a jagged structure), and copying the outer slice copies only the row headers, not the row data. For a dense rectangular matrix with contiguous cells, allocate one flat backing array and slice it into rows, locking each row's capacity with a full slice expression.
Slices and Shared Underlying Arrays: The Subtle Trap
Slicing does not copy data, so a small slice taken from a huge underlying array keeps the entire array alive in memory. When you extract a small result from a large temporary buffer, copy the needed portion into a new slice so the large buffer can be collected.
package main
import (
"fmt"
"os"
)
func firstDigits(filename string) []byte {
bigSlice, err := os.ReadFile(filename)
if err != nil {
return nil
}
// We only need the first 10 bytes, so copy them out.
n := 10
if len(bigSlice) < n {
n = len(bigSlice)
}
result := make([]byte, n)
copy(result, bigSlice[:n])
return result
}
func main() {
fmt.Println(firstDigits("example.txt"))
}
Summary
Slices feel like dynamic arrays but are really controlled views over static memory. Their design gives you the speed of arrays with the flexibility of resizable collections, at the cost of needing to understand the pointer, length, and capacity that live inside every slice header. The key takeaways:
- A slice describes a contiguous segment of an array; it does not own the array.
lentells you what you can read right now;captells you how far you can grow without a reallocation.- Slicing creates new headers, not new data. Use
copywhen you need independence. appendgrows the slice; always capture its return value.- Pre-allocation with
makeand capacity hints reduces allocations in performance-sensitive code.
Slice Type and Structure
Understand the internal structure of a Go slice, the three-field descriptor, and the difference between a nil slice and an empty slice
Creating Slices
Learn how to create slices using literals, the make function, and slicing existing arrays or slices
Slice Expressions
Use simple and full slice expressions to create new slices from arrays slices or pointers to arrays in Go
Slice Length and Capacity
How len and cap reflect a slice's underlying memory, what happens when a slice outgrows its capacity, and why pre-sizing matters for performance.
The append Built-in
How the append function works, how it grows slices, and how to use it correctly in Go.
The copy Built-in
How Go's built-in copy function transfers elements between slices, handles overlapping memory, and avoids common pitfalls.
Two-Dimensional and Nested Slices
Learn how to create and work with two-dimensional slices in Go using row-by-row allocation, single-allocation contiguous memory strategies.
Slices and Shared Underlying Arrays
Learn how Go slices share underlying arrays the aliasing pitfalls that can cause bugs and how to avoid them with full slice expressions and the copy function