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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.