Copy in Go

Copy slice to another slice:

1
2
3
4
5
6
7
8
evens := []int{2, 4}
odds := []int{3, 5, 7}

N := copy(evens, odds)
fmt.Printf("%d element(s) are copied.\n", N)

// evens after copy is, [3, 5]
// odds is intact after copy, [3, 5, 7]

copy can be used over append if want to keep length of target slice intact. If the source slice is bigger in size than destination, copy only copies slice elements that occupies in target slice.

append can be used (like an example below) instead of copy if we are unknown about the size of target slice and want to copy whole slice to it:

1
2
3
4
5
nums := []int{1, 2, 3}

nums := append(nums[:0], []int{4, 5, 6}...)

// nums is [1, 2, 3]