Slices, maps and strings · 3 MIN READ

A slice is a window, not a copied array

Predict a subslice, an element write and append by tracking the backing array.

A slice describes a region of an array. Copying a slice value copies its descriptor, not all the elements. Two descriptors may therefore refer to the same elements while having different lengths and capacities.

01

Draw the shared storage

Treat the array as three numbered cells and each slice as a window over those cells. b begins at the second cell of a. Updating b[0] changes that cell; a observes it because it still refers to the same array.

go
a := []int{10, 20, 30}
b := a[1:3]
b[0] = 99
fmt.Println(a) // [10 99 30]
fmt.Println(b) // [99 30]
Read the code

No goroutines are involved here. This is aliasing in a single execution flow. It matters for helper functions that appear to return a fresh view but actually let their callers change the original data.

02

Capacity affects append, not ownership

Append may reuse storage when capacity is available, or allocate storage when it is not. Assign its result because the returned descriptor can change. A full slice expression can restrict capacity, preventing an append through that view from using the hidden tail; existing element writes still share storage.

go
a := []int{10, 20, 30}
b := a[:1:1] // len 1, cap 1
b = append(b, 40)
b[0] = 7
fmt.Println(a) // [10 20 30]
Read the code

This append must grow beyond b's capacity. Do not depend on a particular capacity growth factor; the language does not promise one.

03

Choose a copy at the ownership boundary

Use slices.Clone for an independent shallow copy of the elements. For slices of pointers or nested slices, the pointed-to objects remain shared. Decide whether you need a view, a shallow clone, or a domain-specific deep copy. Write that decision into the function contract instead of leaving callers to guess.

TAKE THIS WITH YOU

Track array identity as well as len and cap. A different slice value can still expose the same mutable storage.

Check your understanding

Which statement is correct about copying a slice header?

Go to the source

Progress stays in this browser. No account needed.