Junior · Go foundations

Slice copies share storage

Why did appending to one slice change another?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

EXAMPLE · FRAGMENT UNLESS A COMPLETE PROGRAM IS SHOWN

go
base := []int{1, 2, 3}
left := base[:1]
left = append(left, 9)
Reveal a strong answer
  1. Assigning a slice copies its descriptor, not its backing array. Length controls indexing; capacity bounds reslicing and determines whether append can reuse storage.

  2. If capacity permits, append writes into the shared array. Growing beyond capacity creates a new backing array, so code must use the returned slice. The growth factor is not a language contract.

  3. Use copy or slices.Clone when independent storage is required. A full slice expression limits append capacity but still shares the existing elements; it is not a deep copy.

Common trap

A capacity limit prevents append aliasing, but mutation of existing elements is still shared.

Complexity & use

Copying a slice descriptor: O(1). Cloning n elements: O(n) time and storage.

Try it

Predict base after the code, then change left to base[:1:1].

Worked solution

Initially base becomes [1 9 3]. With capacity one, append allocates and base stays [1 2 3]. In both cases assigning left[0] before growth would mutate base[0].

Change the constraint

Explain which assumption would change your choice, and show a test that detects that change.

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.