go / intermediate
Snippet
Controlling Slice Capacity with Three-Index Slicing
Go's three-index slicing slice[low:high:max] limits the capacity of a sub-slice to max - low. This ensures that subsequent append calls exceed capacity and trigger allocation of a new backing array, protecting the original slice from being overwritten.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
package mainimport "fmt"func main() {original := []int{10, 20, 30, 40, 50}subSlice := original[1:3:3]fmt.Printf("subSlice: %v, len: %d, cap: %d\n", subSlice, len(subSlice), cap(subSlice))subSlice = append(subSlice, 99)fmt.Printf("After append -> subSlice: %v, original: %v\n", subSlice, original)}
Breakdown
1
subSlice := original[1:3:3]
Creates a slice from index 1 to 3 with capacity restricted to 2 (3-1).
2
cap(subSlice)
Evaluates to 2, matching the limited maximum capacity.
3
subSlice = append(subSlice, 99)
Triggers reallocation because the append exceeds the capacity of 2.
4
fmt.Printf("After append -> subSlice: %v, original: %v\n", subSlice, original)
Prints both slices to demonstrate that the original remains unmodified.