Duplicate a slice

suggest change

One 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.

Feedback about page:

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



Table Of Contents