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
