Slices Clone Independent Copy
Copy a slice with slices.Clone, then mutate the clone to show that the backing array is independent while nil and capacity keep their own rules.
Code
package main
import (
"fmt"
"slices"
)
func main() {
original := []string{"alpha", "beta", "gamma"}
// slices.Clone copies the elements into a fresh backing array
clone := slices.Clone(original)
fmt.Println("equal after clone:", slices.Equal(original, clone))
clone[0] = "changed"
fmt.Println("original[0]:", original[0])
fmt.Println("clone[0]:", clone[0])
// capacity beyond len is not part of the copy
wide := make([]int, 2, 8)
wide[0], wide[1] = 7, 9
narrow := slices.Clone(wide)
fmt.Println("len/cap:", len(narrow), cap(narrow))
// a nil slice stays nil instead of becoming an empty non-nil slice
var empty []int
fmt.Println("nil stays nil:", slices.Clone(empty) == nil)
}Following the logic downstream
The moving parts are the function main.
Points of care
- No install step: all APIs used ship with the platform.
Applying it
The main signature reads func main()
Each run prints the 3 labeled blocks equal after clone:, original[0]:, clone[0]: in source order.
Statements that matter
wide := make([]int, 2, 8)
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 Slices Clone Independent Copy print when run?
- No setup needed: run the file and look for labeled lines like `equal after clone:`, `original[0]:`, `clone[0]:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.