Restrict capacity with full slice expressions
Restrict capacity with full slice expressions
a[low:high:max] gives length high-low and capacity max-low. The bounds satisfy 0 <= low <= high <= max <= cap(a) for slices, or len(a) as the upper limit for arrays. Only low may be omitted. This expression shares the array without allocating a new one.
package main
import "fmt"
func main() { a := []int{1, 2, 3, 4} s := a[1:3:3] fmt.Println(s, len(s), cap(s)) s[0] = 8 fmt.Println(a)}Capacity is 3-1 = 2. Writes to existing elements still affect the original. Capacity restriction is neither a deep copy nor a read-only view.
Expected output:
[2 3] 2 2[1 8 3 4]Protect a suffix from append
package main
import "fmt"
func main() { a := []int{1, 2, 3, 4} b := append(a[:2], 9) fmt.Println(a, b) c := []int{1, 2, 3, 4} d := append(c[:2:2], 9) fmt.Println(c, d)}The ordinary prefix can grow into the third element. The full expression has capacity 2, forcing a new array on adding a third element. This protects the suffix against that append, not against other writes through aliases.
Expected output:
[1 2 9 4] [1 2 9][1 2 3 4] [1 2 9]Try it locally
From []int{5,6,7,8}, select indexes 1 and 2 with capacity exactly 2. Append 99 and print original and new slice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 07: Restrict capacity with full slice expressions
Check the lesson objective before moving on.
What is cap(a[1:3:4]) for a slice with capacity 5?
What happens when appending one element to s[:len(s):len(s)]?