Duplicate a slice
suggest changeOne option is to allocate a new slice of the same length as original slice and use copy():
main.go
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src)
Output:
src: []int{1, 2, 3}
dst: []int{1, 2, 3}
Another option is to append() original slice to an empty slice:
main.go
src := []int{1, 2, 3}
dst := append([]int(nil), src...)
Output:
src: []int{1, 2, 3}
dst: []int{1, 2, 3}
Both versions are equally efficient.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents