go / expert
Snippet
Capacity-Bounded Slicing via the Three-Index Expression
A two-index slice s[low:high] keeps the original backing array's capacity all the way to its end, so a later append into the returned slice can silently overwrite memory the caller still relies on. The three-index form s[low:high:max] explicitly bounds capacity at max-low. Once full, append must allocate a new array, isolating mutations. This is the standard defence when handing out subslices from buffer pools, request bodies, or shared frames where the consumer is untrusted to leave the parent untouched.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport "fmt"func header(buf []byte) []byte {// s[low:high:max] — cap becomes max-low, so append on// the result cannot stomp the tail of buf in-place.return buf[0:4:4]}func main() {packet := []byte{0xCA, 0xFE, 0xBA, 0xBE,'p', 'a', 'y', 'l', 'o', 'a', 'd'}h := header(packet)fmt.Printf("len=%d cap=%d\n", len(h), cap(h))h = append(h, 0xFF) // allocates a fresh backing arrayfmt.Printf("packet[:4]=%x\n", packet[:4])}
Breakdown
1
return buf[0:4:4]
low=0, high=4, max=4 → len 4, cap 4. The returned slice is full from birth, so any append triggers a fresh allocation.
2
h := header(packet)
Without the third index, h would have cap 11 and silently sharing memory with packet — append could corrupt the payload.
3
h = append(h, 0xFF)
Because cap == len, the runtime grows h into a new backing array; the original packet bytes 4..10 stay intact.
4
fmt.Printf("packet[:4]=%x\n", packet[:4])
Demonstrates isolation: even after appending to h, the parent packet is unchanged — the contract every shared-buffer API needs.