By using the full slice notation b = a[low:high:max]
it is possible to get a slice with a smaller capacity than the assigned slice a
. The capacity of the slice b
will be max - low
and the elements storage will be shared with a
(no copy is made). max - low
must be smaller or equal to cap(a)
, otherwise we get a panic:
a := make([]byte, 8)
b := a[:3:10]
panic: runtime error: slice bounds out of range [::10] with capacity 8
What is the usefulness of the possibility to get a slice with smaller capacity ?
The only useful application I found is to force a copy of the slice with an append
that bypass the capacity of the slice with reduced capacity.
a := []int{1, 2, 3, 4, 5}
b := a[1:3:3]
fmt.Println("a:", a, "b:",b, "cap(b):", cap(b)) // -> a: [1 2 3 4 5] b: [2 3] cap(b): 2
b[0] = 6
fmt.Println("a:", a, "b:",b, "cap(b):", cap(b)) // -> a: [1 6 3 4 5] b: [6 3] cap(b): 2
b = append(b, 7) // copy slice elements and extends capacity of b
fmt.Println("a:", a, "b:",b, "cap(b):", cap(b)) // -> a: [1 6 3 4 5] b: [6 3 7] cap(b): 4
b[1] = 8
fmt.Println("a:", a, "b:",b, "cap(b):", cap(b)) // -> a: [1 6 3 4 5] b: [6 8 7] cap(b): 4
Note that such copy is not obvious and require a comment to make it visible to the reader.
Are the other useful application ?