实现说明
Slice 的 append 扩容与拷贝可以归结为函数 main。
使用要点
- 跑完文件,输出里会留下标记——
first[0] after alias write:、first[0] after copy write:、len=。
常见问题
运行「Slice 的 append 扩容与拷贝」会打印什么?
整个文件跑完,输出行以 first[0] after alias write:、first[0] after copy write:、len= 这类前缀开头。
核心语句
second := append(first, 4) // 可能与 first 共享底层数组
third := make([]int, len(first))
代码示例
package main
import "fmt"
func main() {
first := []int{1, 2, 3}
second := append(first, 4) // 可能与 first 共享底层数组
// 通过 second 修改索引 0,若共享数组则 first 同步变化
second[0] = 100
fmt.Println("first[0] after alias write:", first[0])
// 明确拷贝:目标与源彻底分离
third := make([]int, len(first))
copy(third, first)
third[0] = 7
fmt.Println("first[0] after copy write:", first[0], "third[0]:", third[0])
fmt.Printf("len=%d cap=%d\n", len(second), cap(second))
}