Slice Append Growth And Copy

Control slice backing arrays with append, len, cap, and copy so shared-underlying-array bugs are avoided instead of debugged.

GoData Integrity

Code

gosnippet
20 lines
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))
}

What the file does

Slice Append Growth And Copy is built around the function main.

Applying it

The demo output is labeled (first[0] after alias write:, first[0] after copy write:, len=), so every printed line maps back to its originating operation.

Statements that matter

second := append(first, 4) // 可能与 first 共享底层数组
third := make([]int, len(first))

Interactive Tools for This Topic

FAQ

What does Slice Append Growth And Copy print when run?
Invoke the file as-is — the `first[0] after alias write:`, `first[0] after copy write:`, `len=` prefixes identify which step printed each line.