Clamp Subslice Cap With Three Index Slices

The three-index slice expression clamps cap so append allocates fresh backing arrays instead of silently overwriting elements of the parent slice.

GoData Integrity

Code

gosnippet
22 lines
package main

import "fmt"

func main() {
	// 二下标切片:cap 一直延伸到底层数组末尾,append 会直接写进 base
	base := []int{1, 2, 3, 4, 5, 6, 7, 8}
	head := base[:2]
	head = append(head, 99)
	fmt.Println("plain append overwrote base[2]:", base[2])

	// 三下标 full slice expression base[low:high:max]:cap 被钳到 max-low。
	// 容量不足时 append 立即扩容到新数组,父切片不再被波及
	src := []int{1, 2, 3, 4, 5, 6, 7, 8}
	safe := src[2:4:4]
	safe = append(safe, 99)
	fmt.Println("src[2] untouched:", src[2], "safe:", safe)

	// max-low == high-low 时容量恰好用尽,任何 append 都会触发扩容
	fmt.Printf("safe len=%d cap=%d, src len=%d cap=%d\n",
		len(safe), cap(safe), len(src), cap(src))
}

How it works

Clamp Subslice Cap With Three Index Slices comes down to the function main.

Applying it

Running the file prints labeled results such as plain append overwrote base[2]:, src[2] untouched:, safe len= — each operation’s effect is visible in the output.

Statements that matter

head = append(head, 99)
safe = append(safe, 99)

Interactive Tools for This Topic

FAQ

What does Clamp Subslice Cap With Three Index Slices print when run?
Run it as a complete program — the output lines carry labels such as `plain append overwrote base[2]:`, `src[2] untouched:`, `safe len=`.