Duplicate a slice

suggest change

One option is to allocate a new slice of the same length as original slice and use copy():

src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src)
src: []int{1, 2, 3}
dst: []int{1, 2, 3}

Another option is to append() original slice to an empty slice:

src := []int{1, 2, 3}
dst := append([]int(nil), src...)
src: []int{1, 2, 3}
dst: []int{1, 2, 3}

Both versions are equally efficient.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents