typestar

Slices: length and capacity in Go

A slice is a view: pointer, length, capacity — and append may or may not copy.

func internals() (int, int, bool) {
    backing := make([]int, 0, 8)
    backing = append(backing, 1, 2, 3)

    shared := backing[:2]
    shared = append(shared, 99) // writes into backing[2]
    aliased := backing[2] == 99

    capped := backing[:2:2]
    capped = append(capped, 7) // must allocate: capacity is full

    snapshot := make([]int, len(backing))
    copy(snapshot, backing)

    return len(backing), cap(backing), aliased && capped[2] == 7
}

How it works

  1. append reuses the backing array while capacity allows.
  2. A three-index slice caps the capacity, so append must copy.
  3. copy is how you take a real snapshot.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
418
Tokens
117
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 3 of 9 in Arrays, slices & maps, step 18 of 30 in Language basics.

← Previous Next →