← 中文资源

简体中文版本

三下标切片钳住 cap 防止写穿

二下标切片的 cap 延伸到底层数组末尾,append 会覆盖父切片元素;base[low:high:max] 把 cap 钳住,容量不足立即扩容,父数组不再被波及。

阅读英文原文

实现说明

三下标切片钳住 cap 防止写穿以函数 main为骨架。

使用要点

  • 演示输出是带标签的(plain append overwrote base[2]:、src[2] untouched:、safe len=),每个操作都会留下自己的一行标注。

常见问题

运行「三下标切片钳住 cap 防止写穿」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 plain append overwrote base[2]:、src[2] untouched:、safe len= 这类标签。

核心语句

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

代码示例

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))
}