liveBook · Manning

Full slice expression

As explained in 100 Go Mistakes and How to Avoid Them

A full slice expression is Go slice syntax with low, high, and maximum indices that sets the resulting slice capacity to max minus low.

A full slice expression uses s[low:high:max]. It creates the same visible range as s[low:high], but sets capacity to max minus low. This matters when passing a slice to code that may append: s[:2] can expose the third element through spare capacity, while s[:2:2] prevents that append from reusing the original array. section 3.9

Preventing append from changing the original slice

With s := []int{1, 2, 3}, calling f(s[:2]) lets f's append(s, 10) overwrite the third element, producing [1 2 10]. Calling f(s[:2:2]) gives f a two-element, two-capacity slice, so append must allocate instead of modifying s. Use this when limiting side effects matters and an extra copy is undesirable. section 3.9

Choose the technique according to the problem:

  • Use a full slice expression to restrict append-related effects to the selected range without copying. section 3.9
  • Use a slice copy when retaining only a small part of a large slice; limiting capacity with s[:5:5] does not make the unused backing array reclaimable. section 3.10.1
func main() {
    s := []int{1, 2, 3}
    f(s[:2:2])            #1
    // Use s
}
 
func f(s []int) {
    // Update s
}

Compare the defensive call f(s[:2:2]) with the ordinary s[:2] form to see how capacity controls append behavior. section 3.9

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines the low-high-max form, traces capacity arithmetic, and stops short of making it a solution for backing-array retention.
Examples
Uses s[:2] versus s[:2:2], append(s, 10), and large message slices retaining million-byte backing arrays.
What it assumes
Assumes familiarity with slice length, capacity, append, shared backing arrays, and copying.
What you can do after
Diagnose/debug with it by separating append-related mutations from memory retention and choosing a bounded slice or copy.
How it connects
Connects slices with append, backing arrays, slice copying, and garbage collection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.