Module lessons (2/5)
Slice: the idiomatic structure
make, append, len/cap, slicing s[a:b], share of the underlying array and when to copy.
What you'll learn in this lesson
- Distinguish
len(visible elements) fromcap(capacity of the underlying backing array) in the header of a slice. - Preallocate with
make([]T, len, cap)and enqueue elements always assigning the result ofappend. - Isolate unwanted mutations on sub-slices via
copyor full-slice expressions[a:b:b].
Overview
A slice []T is Go's standard dynamic sequence. Internally it is a lightweight structure of just three fields (slice header): a pointer to the backing array, the current length (len), and the maximum capacity before having to reallocate (cap).
When len == cap and you call append, the Go runtime allocates a new, larger backing array, copies the old elements into it, and returns a new slice header. This is why you must always assign the value returned by append:
Sections covered in this lesson
- 1Creation with literal,
makeandnil - 2
appendand doubling the capacity - 3Sub-slice
s[a:b]and independent copy withcopy - 4Pre-allocation vs dynamic growth in action
- 5Guided practice
- 6Check for understanding
Unlock "Slice: the idiomatic structure" and the full Course Go curriculum
`make`, `append`, len/cap, slicing `s[a:b]`, share of the underlying array and when to copy.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.