Skip to main content
Module 4 · Lesson 2 of 517/50 in the course~15 min
Module lessons (2/5)

Slice: the idiomatic structure

Lesson preview5 hands-on exercises readyCourse Go · Module 4 — Collections

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) from cap (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 of append.
  • Isolate unwanted mutations on sub-slices via copy or full-slice expression s[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

  1. 1Creation with literal, make and nil
  2. 2append and doubling the capacity
  3. 3Sub-slice s[a:b] and independent copy with copy
  4. 4Pre-allocation vs dynamic growth in action
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 4 — Collections

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.